# -*- coding: utf-8 -*-
"""
Notifications App Configuration

This module configures the notifications Django app, including
app metadata, signal connections, and initialization tasks.

The app provides comprehensive notification functionality including:
- In-app notifications
- Email notifications
- User preferences
- Template management
- Asynchronous delivery via Celery

Author: AdTlas Development Team
Version: 1.0.0
Last Updated: 2024
"""

import logging
from django.apps import AppConfig
from django.db.models.signals import post_migrate
from django.conf import settings

logger = logging.getLogger(__name__)


class NotificationsConfig(AppConfig):
    """
    Configuration class for the notifications app.
    
    This class handles app initialization, signal connections,
    and setup of default notification types and templates.
    """
    
    # App configuration
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'apps.notifications'
    verbose_name = 'Notifications'
    
    # App metadata
    description = 'Comprehensive notification system with in-app and email support'
    version = '1.0.0'
    author = 'AdTlas Development Team'
    
    def ready(self):
        """
        Called when the app is ready.
        
        This method sets up signal handlers, imports tasks,
        and performs other initialization tasks.
        """
        try:
            # Import signal handlers
            from . import signals
            
            # Import Celery tasks to register them
            from . import tasks
            
            # Connect post-migrate signal for initial setup
            post_migrate.connect(
                self.create_default_notification_types,
                sender=self
            )
            
            post_migrate.connect(
                self.create_default_templates,
                sender=self
            )
            
            # Setup logging
            self.setup_logging()
            
            logger.info(f'Notifications app ({self.version}) initialized successfully')
            
        except Exception as e:
            logger.error(f'Error initializing notifications app: {e}')
    
    def create_default_notification_types(self, sender, **kwargs):
        """
        Create default notification types after migration.
        
        Args:
            sender: The sender of the signal
            **kwargs: Additional keyword arguments
        """
        try:
            from .models import NotificationType
            from . import NOTIFICATION_TYPES
            
            created_count = 0
            
            for type_code, type_config in NOTIFICATION_TYPES.items():
                notification_type, created = NotificationType.objects.get_or_create(
                    code=type_code,
                    defaults={
                        'name': type_config['name'],
                        'description': type_config['description'],
                        'icon': type_config.get('icon', 'fas fa-bell'),
                        'color': type_config.get('color', 'primary'),
                        'is_active': True,
                        'default_enabled': type_config.get('default_enabled', True),
                        'can_be_disabled': True,
                    }
                )
                
                if created:
                    created_count += 1
                    logger.info(f'Created notification type: {type_code}')
            
            if created_count > 0:
                logger.info(f'Created {created_count} default notification types')
            
        except Exception as e:
            logger.error(f'Error creating default notification types: {e}')
    
    def create_default_templates(self, sender, **kwargs):
        """
        Create default notification templates after migration.
        
        Args:
            sender: The sender of the signal
            **kwargs: Additional keyword arguments
        """
        try:
            from .models import NotificationTemplate
            
            # Default email templates
            email_templates = [
                {
                    'name': 'default',
                    'template_type': 'email',
                    'subject': '{{ title }}',
                    'html_content': self._get_default_email_html_template(),
                    'text_content': self._get_default_email_text_template(),
                    'description': 'Default email notification template',
                },
                {
                    'name': 'welcome',
                    'template_type': 'email',
                    'subject': 'Welcome to {{ site_name }}!',
                    'html_content': self._get_welcome_email_html_template(),
                    'text_content': self._get_welcome_email_text_template(),
                    'description': 'Welcome email template for new users',
                },
                {
                    'name': 'password_reset',
                    'template_type': 'email',
                    'subject': 'Password Reset Request - {{ site_name }}',
                    'html_content': self._get_password_reset_html_template(),
                    'text_content': self._get_password_reset_text_template(),
                    'description': 'Password reset email template',
                },
                {
                    'name': 'security_alert',
                    'template_type': 'email',
                    'subject': 'Security Alert - {{ site_name }}',
                    'html_content': self._get_security_alert_html_template(),
                    'text_content': self._get_security_alert_text_template(),
                    'description': 'Security alert email template',
                },
            ]
            
            # Default in-app templates
            inapp_templates = [
                {
                    'name': 'default',
                    'template_type': 'in_app',
                    'subject': '{{ title }}',
                    'html_content': '<div class="notification-content">{{ message }}</div>',
                    'text_content': '{{ message }}',
                    'description': 'Default in-app notification template',
                },
                {
                    'name': 'system_announcement',
                    'template_type': 'in_app',
                    'subject': '{{ title }}',
                    'html_content': self._get_system_announcement_template(),
                    'text_content': '{{ message }}',
                    'description': 'System announcement in-app template',
                },
            ]
            
            created_count = 0
            
            # Create email templates
            for template_data in email_templates:
                template, created = NotificationTemplate.objects.get_or_create(
                    name=template_data['name'],
                    template_type=template_data['template_type'],
                    defaults=template_data
                )
                
                if created:
                    created_count += 1
                    logger.info(f'Created email template: {template_data["name"]}')
            
            # Create in-app templates
            for template_data in inapp_templates:
                template, created = NotificationTemplate.objects.get_or_create(
                    name=template_data['name'],
                    template_type=template_data['template_type'],
                    defaults=template_data
                )
                
                if created:
                    created_count += 1
                    logger.info(f'Created in-app template: {template_data["name"]}')
            
            if created_count > 0:
                logger.info(f'Created {created_count} default notification templates')
            
        except Exception as e:
            logger.error(f'Error creating default notification templates: {e}')
    
    def setup_logging(self):
        """
        Setup logging configuration for the notifications app.
        """
        try:
            # Configure logging if not already configured
            if not logger.handlers:
                import logging.config
                from . import LOGGING_CONFIG
                
                # Only configure if logging config is provided
                if hasattr(settings, 'LOGGING'):
                    # Use Django's logging configuration
                    pass
                else:
                    # Use our default configuration
                    logging.config.dictConfig(LOGGING_CONFIG)
            
        except Exception as e:
            print(f'Error setting up logging for notifications app: {e}')
    
    def _get_default_email_html_template(self):
        """
        Get the default HTML email template.
        
        Returns:
            str: HTML template content
        """
        return '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background-color: #007bff;
            color: white;
            padding: 20px;
            text-align: center;
            border-radius: 5px 5px 0 0;
        }
        .content {
            background-color: #f8f9fa;
            padding: 30px;
            border-radius: 0 0 5px 5px;
        }
        .footer {
            text-align: center;
            margin-top: 20px;
            font-size: 12px;
            color: #666;
        }
        .button {
            display: inline-block;
            background-color: #007bff;
            color: white;
            padding: 12px 24px;
            text-decoration: none;
            border-radius: 5px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>{{ site_name }}</h1>
    </div>
    <div class="content">
        <h2>{{ title }}</h2>
        <p>{{ message }}</p>
        {% if action_url %}
        <p>
            <a href="{{ action_url }}" class="button">Take Action</a>
        </p>
        {% endif %}
    </div>
    <div class="footer">
        <p>&copy; {{ current_year }} {{ company_name }}. All rights reserved.</p>
        <p>If you have any questions, contact us at {{ support_email }}</p>
    </div>
</body>
</html>
        '''
    
    def _get_default_email_text_template(self):
        """
        Get the default text email template.
        
        Returns:
            str: Text template content
        """
        return '''
{{ site_name }}

{{ title }}

{{ message }}

{% if action_url %}
Take Action: {{ action_url }}
{% endif %}

---
© {{ current_year }} {{ company_name }}. All rights reserved.
If you have any questions, contact us at {{ support_email }}
        '''
    
    def _get_welcome_email_html_template(self):
        """
        Get the welcome email HTML template.
        
        Returns:
            str: HTML template content
        """
        return '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to {{ site_name }}!</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background: linear-gradient(135deg, #007bff, #28a745);
            color: white;
            padding: 30px;
            text-align: center;
            border-radius: 10px 10px 0 0;
        }
        .content {
            background-color: #f8f9fa;
            padding: 30px;
            border-radius: 0 0 10px 10px;
        }
        .welcome-message {
            font-size: 18px;
            margin-bottom: 20px;
        }
        .features {
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            margin: 20px 0;
        }
        .button {
            display: inline-block;
            background: linear-gradient(135deg, #007bff, #28a745);
            color: white;
            padding: 15px 30px;
            text-decoration: none;
            border-radius: 25px;
            margin: 20px 0;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🎉 Welcome to {{ site_name }}!</h1>
        <p>We're excited to have you on board, {{ user.first_name }}!</p>
    </div>
    <div class="content">
        <div class="welcome-message">
            <p>Hello {{ user.first_name }},</p>
            <p>Thank you for joining {{ site_name }}! Your account has been successfully created and you're ready to get started.</p>
        </div>
        
        <div class="features">
            <h3>What you can do with {{ site_name }}:</h3>
            <ul>
                <li>📊 Access powerful analytics and insights</li>
                <li>🔒 Secure account management</li>
                <li>📱 Real-time notifications</li>
                <li>👥 Collaborate with your team</li>
                <li>📈 Track your progress</li>
            </ul>
        </div>
        
        <p style="text-align: center;">
            <a href="{{ action_url }}" class="button">Get Started Now</a>
        </p>
        
        <p>If you have any questions or need help getting started, don't hesitate to reach out to our support team at {{ support_email }}.</p>
        
        <p>Welcome aboard!</p>
        <p>The {{ site_name }} Team</p>
    </div>
</body>
</html>
        '''
    
    def _get_welcome_email_text_template(self):
        """
        Get the welcome email text template.
        
        Returns:
            str: Text template content
        """
        return '''
Welcome to {{ site_name }}!

Hello {{ user.first_name }},

Thank you for joining {{ site_name }}! Your account has been successfully created and you're ready to get started.

What you can do with {{ site_name }}:
- Access powerful analytics and insights
- Secure account management
- Real-time notifications
- Collaborate with your team
- Track your progress

Get Started: {{ action_url }}

If you have any questions or need help getting started, don't hesitate to reach out to our support team at {{ support_email }}.

Welcome aboard!
The {{ site_name }} Team
        '''
    
    def _get_password_reset_html_template(self):
        """
        Get the password reset HTML template.
        
        Returns:
            str: HTML template content
        """
        return '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Password Reset Request</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background-color: #dc3545;
            color: white;
            padding: 20px;
            text-align: center;
            border-radius: 5px 5px 0 0;
        }
        .content {
            background-color: #f8f9fa;
            padding: 30px;
            border-radius: 0 0 5px 5px;
        }
        .security-notice {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
        }
        .button {
            display: inline-block;
            background-color: #dc3545;
            color: white;
            padding: 15px 30px;
            text-decoration: none;
            border-radius: 5px;
            margin: 20px 0;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🔒 Password Reset Request</h1>
    </div>
    <div class="content">
        <p>Hello {{ user.first_name }},</p>
        
        <p>We received a request to reset your password for your {{ site_name }} account.</p>
        
        <div class="security-notice">
            <strong>Security Notice:</strong> If you didn't request this password reset, please ignore this email. Your password will remain unchanged.
        </div>
        
        <p>To reset your password, click the button below:</p>
        
        <p style="text-align: center;">
            <a href="{{ action_url }}" class="button">Reset My Password</a>
        </p>
        
        <p>Or copy and paste this link into your browser:</p>
        <p style="word-break: break-all; background-color: #e9ecef; padding: 10px; border-radius: 3px;">{{ action_url }}</p>
        
        <p>This link will expire in 24 hours for security reasons.</p>
        
        <p>If you continue to have problems, please contact our support team at {{ support_email }}.</p>
        
        <p>Best regards,<br>The {{ site_name }} Team</p>
    </div>
</body>
</html>
        '''
    
    def _get_password_reset_text_template(self):
        """
        Get the password reset text template.
        
        Returns:
            str: Text template content
        """
        return '''
Password Reset Request - {{ site_name }}

Hello {{ user.first_name }},

We received a request to reset your password for your {{ site_name }} account.

SECURITY NOTICE: If you didn't request this password reset, please ignore this email. Your password will remain unchanged.

To reset your password, visit this link:
{{ action_url }}

This link will expire in 24 hours for security reasons.

If you continue to have problems, please contact our support team at {{ support_email }}.

Best regards,
The {{ site_name }} Team
        '''
    
    def _get_security_alert_html_template(self):
        """
        Get the security alert HTML template.
        
        Returns:
            str: HTML template content
        """
        return '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Security Alert</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background-color: #dc3545;
            color: white;
            padding: 20px;
            text-align: center;
            border-radius: 5px 5px 0 0;
        }
        .content {
            background-color: #f8f9fa;
            padding: 30px;
            border-radius: 0 0 5px 5px;
        }
        .alert-box {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
        }
        .button {
            display: inline-block;
            background-color: #dc3545;
            color: white;
            padding: 15px 30px;
            text-decoration: none;
            border-radius: 5px;
            margin: 20px 0;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🚨 Security Alert</h1>
    </div>
    <div class="content">
        <p>Hello {{ user.first_name }},</p>
        
        <div class="alert-box">
            <strong>Security Alert:</strong> {{ message }}
        </div>
        
        <p>We detected unusual activity on your {{ site_name }} account and wanted to notify you immediately.</p>
        
        <p><strong>Details:</strong></p>
        <ul>
            <li><strong>Time:</strong> {{ timestamp }}</li>
            <li><strong>IP Address:</strong> {{ ip_address }}</li>
            <li><strong>Location:</strong> {{ location }}</li>
            <li><strong>Device:</strong> {{ user_agent }}</li>
        </ul>
        
        <p>If this was you, you can safely ignore this email. If you don't recognize this activity, please take action immediately:</p>
        
        <p style="text-align: center;">
            <a href="{{ action_url }}" class="button">Secure My Account</a>
        </p>
        
        <p>For immediate assistance, contact our security team at {{ support_email }}.</p>
        
        <p>Stay safe,<br>The {{ site_name }} Security Team</p>
    </div>
</body>
</html>
        '''
    
    def _get_security_alert_text_template(self):
        """
        Get the security alert text template.
        
        Returns:
            str: Text template content
        """
        return '''
Security Alert - {{ site_name }}

Hello {{ user.first_name }},

SECURITY ALERT: {{ message }}

We detected unusual activity on your {{ site_name }} account and wanted to notify you immediately.

Details:
- Time: {{ timestamp }}
- IP Address: {{ ip_address }}
- Location: {{ location }}
- Device: {{ user_agent }}

If this was you, you can safely ignore this email. If you don't recognize this activity, please take action immediately:

Secure My Account: {{ action_url }}

For immediate assistance, contact our security team at {{ support_email }}.

Stay safe,
The {{ site_name }} Security Team
        '''
    
    def _get_system_announcement_template(self):
        """
        Get the system announcement in-app template.
        
        Returns:
            str: HTML template content
        """
        return '''
<div class="notification-content system-announcement">
    <div class="notification-icon">
        <i class="fas fa-bullhorn text-primary"></i>
    </div>
    <div class="notification-body">
        <h5 class="notification-title">{{ title }}</h5>
        <p class="notification-message">{{ message }}</p>
        {% if action_url %}
        <a href="{{ action_url }}" class="btn btn-sm btn-primary">Learn More</a>
        {% endif %}
    </div>
    <div class="notification-meta">
        <small class="text-muted">{{ created_at|date:"M d, Y H:i" }}</small>
    </div>
</div>
        '''