# -*- coding: utf-8 -*-
"""
Core Views Module

This module contains views for the core app including landing pages,
dashboard, error pages, and common functionality used across the application.
"""

import time 
import json
import logging
from django.db import connection
from django.conf import settings
from django.utils import timezone 
from django.core.cache import cache
from django.http import JsonResponse
from django.db.models import Count, Q
from datetime import datetime, timedelta
from django.shortcuts import render, redirect
from django.urls import reverse_lazy, reverse
from django.views.generic import View, TemplateView
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page 
from django.utils.translation import gettext_lazy as _ 
from django.contrib.auth.decorators import login_required  
from django.contrib.auth.mixins import LoginRequiredMixin 
from django.views.decorators.csrf import csrf_protect
from django.middleware.csrf import get_token

from apps.common.utils import is_ajax_request
from apps.campaigns.models import Campaign
from apps.advertisers.models import Advertiser
from apps.channels.models import Channel
from apps.playlists.models import Playlist
from apps.core.models import ActivityLog, Newsletter, ContactMessage
from apps.accounts.models import User, Role
from apps.core.forms import NewsletterForm, ContactForm
# from apps.authentication.models import LoginAttempt, UserSession 
from apps.common.utils import is_ajax_request

# Set up logging
logger = logging.getLogger(__name__)


def get_client_info(request):
    """Get client IP and user agent."""
    from apps.common.utils import get_client_ip
    return {
        'ip_address': get_client_ip(request),
        'user_agent': request.META.get('HTTP_USER_AGENT', '')
    }


class LandingView(View):
    """
    Landing Page View

    This view is responsible for rendering the landing page of the application.
    It extends the Django View class and defines the HTTP GET method to handle
    the request and return the rendered landing page template.

    Methods:
        get(request): Handles the HTTP GET request and returns the rendered
            landing page template.

    Template:
        - 'landing.html': The HTML template used to render the landing page.

    """ 
 
    http_method_names = ["get"]
    template_name = "landing/index.html"
    extra_context = {
        "title": "Adtlas: Advanced TV Advertising Solutions",
        "author": " Adtlas Development Team", 
        "description": "Adtlas specializes in TV advertising solutions, offering data-driven campaign management, real-time analytics, and programmatic ad technology to optimize your advertising strategy.",
        "keywords": "Adtlas, TV advertising solutions, data-driven advertising, real-time analytics, programmatic advertising, campaign management, viewer analytics, ad optimization, API integration, VAST, digital advertising, media buying, targeted ad placement, audience engagement",
        "version": "2.0.0",
    }

    def get_context_data(self, **kwargs):
        """
        Add context data for the home page.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        """
        context = super().get_context_data(**kwargs)
        
        # Add application statistics for landing page
        context.update({
            "title": _("Home"),
            "total_users": self.get_total_users(),
            "app_name": getattr(settings, "APP_NAME", "Django App"),
            "app_version": getattr(settings, "APP_VERSION", "1.0.0"),
            "features": self.get_app_features(),
            "testimonials": self.get_testimonials(),
        })
        
        return context

    def get_app_features(self):
        """
        Get list of application features for display.
        
        Returns:
            list: List of feature dictionaries
        """
        return [
            {
                "title": _("User Management"),
                "description": _("Comprehensive user account management with roles and permissions"),
                "icon": "fas fa-users"
            },
            {
                "title": _("Secure Authentication"),
                "description": _("Advanced authentication with session management and security features"),
                "icon": "fas fa-shield-alt"
            },
            {
                "title": _("Role-Based Access"),
                "description": _("Dynamic role and permission system for flexible access control"),
                "icon": "fas fa-key"
            },
            {
                "title": _("Dashboard Analytics"),
                "description": _("Comprehensive dashboard with real-time analytics and insights"),
                "icon": "fas fa-chart-bar"
            }
        ]
    
    def get_testimonials(self):
        """
        Get testimonials for the landing page.
        
        Returns:
            list: List of testimonial dictionaries
        """
        return [
            {
                "name": "John Doe",
                "role": "Project Manager",
                "content": "This application has streamlined our user management process significantly.",
                "rating": 5
            },
            {
                "name": "Jane Smith",
                "role": "System Administrator",
                "content": "The security features and role management are exactly what we needed.",
                "rating": 5
            }
        ]

    def get(self, request, *args, **kwargs):
        """
        Handles the HTTP GET request and returns the rendered landing page template.

        Args:
            request (HttpRequest): The HTTP request object.

        Returns:
            HttpResponse: The rendered landing page template.
        """

        if request.user.is_authenticated:
            return redirect("core:dashboard")
 
        return render(request, self.template_name, self.extra_context)


@method_decorator(csrf_protect, name='dispatch')
class NewsletterView(View):
    """Handle newsletter subscription via AJAX."""
    
    def post(self, request, *args, **kwargs):
        """Handle POST request for newsletter subscription."""
        try:
            # Parse JSON data
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
            
            # Create form instance
            form = NewsletterForm(data)
            
            if form.is_valid():
                email = form.cleaned_data['email']
                
                # Check if already subscribed
                existing = Newsletter.objects.filter(email=email).first()
                
                if existing:
                    if existing.is_subscribed:
                        return JsonResponse({
                            'success': False,
                            'type': 'warning',
                            'message': 'You are already subscribed to our newsletter.',
                            'title': 'Already Subscribed'
                        }, status=400)
                    else:
                        # Resubscribe
                        existing.resubscribe()
                        newsletter = existing
                        action = 'resubscribed'
                else:
                    # Create new subscription
                    newsletter = form.save(commit=False)
                    client_info = get_client_info(request)
                    newsletter.ip_address = client_info['ip_address']
                    newsletter.user_agent = client_info['user_agent']
                    newsletter.source = 'website'
                    newsletter.save()
                    action = 'subscribed'
                
                logger.info(f"Newsletter {action}: {email}")
                
                return JsonResponse({
                    'success': True,
                    'type': 'success',
                    'message': f'Successfully {action} to our newsletter!',
                    'title': 'Subscription Successful',
                    'email': email
                })
            
            else:
                # Form validation errors
                errors = {}
                for field, field_errors in form.errors.items():
                    errors[field] = field_errors
                
                return JsonResponse({
                    'success': False,
                    'type': 'error',
                    'message': 'Please correct the errors below.',
                    'title': 'Validation Error',
                    'errors': errors
                }, status=400)
        
        except json.JSONDecodeError:
            return JsonResponse({
                'success': False,
                'type': 'error',
                'message': 'Invalid JSON data.',
                'title': 'Invalid Request'
            }, status=400)
        
        except Exception as e:
            logger.error(f"Newsletter subscription error: {str(e)}")
            return JsonResponse({
                'success': False,
                'type': 'error',
                'message': 'An error occurred. Please try again later.',
                'title': 'Server Error'
            }, status=500)


@method_decorator(csrf_protect, name='dispatch')
class ContactView(View):
    """Handle contact form submission via AJAX."""
    
    def post(self, request, *args, **kwargs):
        """Handle POST request for contact form."""
        try:
            # Parse JSON data
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
            
            # Create form instance
            form = ContactForm(data)
            
            if form.is_valid():
                # Save contact message
                contact = form.save(commit=False)
                client_info = get_client_info(request)
                contact.ip_address = client_info['ip_address']
                contact.user_agent = client_info['user_agent']
                contact.source = 'website'
                contact.save()
                
                # Handle newsletter subscription if requested
                if contact.is_newsletter_signup:
                    try:
                        newsletter_data = {
                            'email': contact.email,
                            'first_name': contact.name.split()[0] if contact.name else '',
                            'last_name': ' '.join(contact.name.split()[1:]) if len(contact.name.split()) > 1 else ''
                        }
                        newsletter_form = NewsletterForm(newsletter_data)
                        
                        if newsletter_form.is_valid():
                            newsletter, created = Newsletter.objects.get_or_create(
                                email=contact.email,
                                defaults={
                                    'first_name': newsletter_data['first_name'],
                                    'last_name': newsletter_data['last_name'],
                                    'ip_address': client_info['ip_address'],
                                    'user_agent': client_info['user_agent'],
                                    'source': 'contact_form'
                                }
                            )
                            
                            if not created and not newsletter.is_subscribed:
                                newsletter.resubscribe()
                    
                    except Exception as e:
                        logger.warning(f"Newsletter subscription from contact form failed: {str(e)}")
                
                logger.info(f"Contact form submission from: {contact.email}")
                
                return JsonResponse({
                    'success': True,
                    'type': 'success',
                    'message': 'Thank you for your message! We will get back to you soon.',
                    'title': 'Message Sent Successfully',
                    'contact_id': str(contact.id)
                })
            
            else:
                # Form validation errors
                errors = {}
                for field, field_errors in form.errors.items():
                    errors[field] = field_errors
                
                return JsonResponse({
                    'success': False,
                    'type': 'error',
                    'message': 'Please correct the errors below.',
                    'title': 'Validation Error',
                    'errors': errors
                }, status=400)
        
        except json.JSONDecodeError:
            return JsonResponse({
                'success': False,
                'type': 'error',
                'message': 'Invalid JSON data.',
                'title': 'Invalid Request'
            }, status=400)
        
        except Exception as e:
            logger.error(f"Contact form error: {str(e)}")
            return JsonResponse({
                'success': False,
                'type': 'error',
                'message': 'An error occurred. Please try again later.',
                'title': 'Server Error'
            }, status=500)


class AboutView(TemplateView):
    """
    About page view.
    
    Displays information about the application, team, and company.
    """
    
    template_name = "core/about.html"
    
    def get_context_data(self, **kwargs):
        """
        Add about page context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        """
        context = super().get_context_data(**kwargs)
        
        context.update({
            "title": _("About Us"),
            "app_info": self.get_app_info(),
            "team_members": self.get_team_members(),
            "company_info": self.get_company_info(),
        })
        
        return context
    
    def get_app_info(self):
        """
        Get application information.
        
        Returns:
            dict: Application information
        """
        return {
            "name": getattr(settings, "APP_NAME", "Django Application"),
            "version": getattr(settings, "APP_VERSION", "1.0.0"),
            "description": "A professional Django application with user management and authentication.",
            "technologies": ["Django", "Python", "PostgreSQL", "Redis", "Bootstrap"],
            "launch_date": "2024"
        }
    
    def get_team_members(self):
        """
        Get team member information.
        
        Returns:
            list: List of team member dictionaries
        """
        return [
            {
                "name": "Senior Django Developer",
                "role": "Lead Developer",
                "bio": "Experienced Django developer with expertise in building scalable web applications.",
                "avatar": "/static/images/team/developer.jpg"
            }
        ]
    
    def get_company_info(self):
        """
        Get company information.
        
        Returns:
            dict: Company information
        """
        return {
            "name": "Your Company Name",
            "founded": "2024",
            "mission": "To provide excellent software solutions that help businesses grow.",
            "values": ["Innovation", "Quality", "Customer Focus", "Integrity"]
        }


class PrivacyPolicyView(View):
    """
    Privacy Policy Page View

    This view is responsible for rendering the privacy policy page of the application.
    It extends the Django View class and defines the HTTP GET method to handle
    the request and return the rendered privacy policy page template.

    Methods:
        get(request): Handles the HTTP GET request and returns the rendered
            privacy policy page template.

    Template:
        - 'privacy.html': The HTML template used to render the privacy policy page.

    """
    http_method_names = ["get"]
    template_name = "landing/privacy.html"
    extra_context = {
        "title": "Privacy Policy - Adtlas",
        "author": " Adtlas Development Team", 
        "description": "Privacy Policy for Adtlas TV advertising solutions. This policy explains how we collect, use, and protect your personal information.",
        "keywords": "Adtlas, privacy policy, TV advertising solutions, personal information, data collection, usage, protection",
    }

    def get_context_data(self, **kwargs):
        """
        Add privacy page context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        """
        context = super().get_context_data(**kwargs)
        
        context.update({
            "title": _("Privacy Policy"),
        })
        
        return context

    def get(self, request, *args, **kwargs):
        """
        Handles the HTTP GET request and returns the rendered privacy policy page template.

        Args:
            request (HttpRequest): The HTTP request object.

        Returns:
            HttpResponse: The rendered privacy policy page template.
        """
        return render(request, self.template_name, self.extra_context)


class TermsConditionsView(View):
    """
    Terms and Conditions Page View

    This view is responsible for rendering the terms and conditions page of the application.
    It extends the Django View class and defines the HTTP GET method to handle
    the request and return the rendered terms and conditions page template.

    Methods:
        get(request): Handles the HTTP GET request and returns the rendered
            terms and conditions page template.

    Template:
        - 'terms.html': The HTML template used to render the terms and conditions page.

    """
    http_method_names = ["get"]
    template_name = "landing/terms.html"
    extra_context = {
        "title": "Terms and Conditions - Adtlas",
        "author": " Adtlas Development Team", 
        "description": "Terms and Conditions for Adtlas TV advertising solutions. Please read these terms carefully before using our services.",
        "keywords": "Adtlas, terms and conditions, TV advertising solutions, usage, restrictions, liability, disclaimer, terms of service",
    }

    def get_context_data(self, **kwargs):
        """
        Add terms of service page context data.
        """
        context = super().get_context_data(**kwargs)
        context.update({
            "title": _("Terms of Service"),
        })
        return context

    def get(self, request, *args, **kwargs):
        """
        Handles the HTTP GET request and returns the rendered terms and conditions page template.

        Args:
            request (HttpRequest): The HTTP request object.

        Returns:
            HttpResponse: The rendered terms and conditions page template.
        """
        return render(request, self.template_name, self.extra_context)


class DashboardView(LoginRequiredMixin, View):
    """
    Dashboard View

    This view is responsible for rendering the dashboard page of the application.
    It extends the Django View class and defines the HTTP GET method to handle
    the request and return the rendered dashboard page template.

    Methods:
        get(request): Handles the HTTP GET request and returns the rendered
            dashboard page template.

    Template:
        - 'dashboard.html': The HTML template used to render the dashboard page.

    """
    http_method_names = ["get"]
    template_name = "core/dashboard.html"
    extra_context = {
        "title": "Dashboard - Adtlas",
        "author": " Adtlas Development Team", 
        "description": "Adtlas TV advertising solutions dashboard. Manage and monitor your campaigns, advertisers, and channels.",
        "keywords": "Adtlas, dashboard, TV advertising solutions, campaigns, advertisers, channels, monitoring",
    }

    def get_context_data(self, **kwargs):
        """
        Add dashboard page context data.
        """
        context = super().get_context_data(**kwargs)
        context.update({
            "title": _("Dashboard"),
        })
        return context
    
    def get(self, request, *args, **kwargs):
        """
        Handles the HTTP GET request and returns the rendered dashboard page template.

        Args:
            request (HttpRequest): The HTTP request object.

        Returns:
            HttpResponse: The rendered dashboard page template.
        """
        # Get user's dashboard data
        user = request.user
        dashboard_data = self.get_dashboard_data(user)
        
        # Update context with dashboard data
        self.extra_context.update(dashboard_data)
        
        # Render dashboard template
        return render(request, self.template_name, self.extra_context)
    
    def get_dashboard_data(self, user):
        """
        Get user's dashboard data.
        
        Args:
            user (User): The user object.
            
        Returns:
            dict: Dashboard data for the user.
        """
        # Get date range for statistics (last 30 days)
        end_date = timezone.now()
        start_date = end_date - timedelta(days=30)
        
        # Basic statistics
        stats = {
            'total_campaigns': Campaign.objects.filter(is_deleted=False).count(),
            'active_campaigns': Campaign.objects.filter(
                is_deleted=False, 
                status='active',
                start_date__lte=end_date,
                end_date__gte=start_date
            ).count(),
            'total_advertisers': Advertiser.objects.filter(is_deleted=False).count(),
            'total_channels': Channel.objects.filter(is_deleted=False).count(),
            'total_playlists': Playlist.objects.filter(is_deleted=False).count(),
            'total_impressions': 0,  # TODO: Implement when impressions tracking is added
            'total_revenue': 0,  # TODO: Implement when revenue tracking is added
            'channels_growth': 5.2,  # Mock data for now
            'campaigns_change': -2.1,  # Mock data for now
            'impressions_growth': 12.5,  # Mock data for now
            'revenue_growth': 8.3,  # Mock data for now
        }
        
        # Recent activities
        recent_activities = ActivityLog.objects.select_related('user').order_by('-created_at')[:10]
        
        # Campaign status distribution
        campaign_status = Campaign.objects.filter(is_deleted=False).aggregate(
            active=Count('id', filter=Q(status='active')),
            inactive=Count('id', filter=~Q(status='active')),
        )
        
        # Recent campaigns with mock impression and revenue data
        recent_campaigns = Campaign.objects.filter(
            is_deleted=False
        ).select_related('brand').order_by('-created_at')[:5]
        
        # Add mock data to campaigns
        for campaign in recent_campaigns:
            campaign.impressions_count = 0  # TODO: Implement actual impressions tracking
            campaign.revenue = 0  # TODO: Implement actual revenue tracking
        
        # Top performing channels with mock data
        top_channels = Channel.objects.filter(is_deleted=False)[:5]
        for channel in top_channels:
            channel.impressions_count = 0  # TODO: Implement actual impressions tracking
            channel.revenue = 0  # TODO: Implement actual revenue tracking
            channel.performance = 75  # Mock performance percentage
        
        # Chart data for impressions (mock data for now)
        chart_data = {
            'impressions': [120, 150, 180, 200, 175, 220, 250],
            'dates': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        }
        
        dashboard_data = {
            'stats': stats,
            'recent_activities': recent_activities,
            'activity_logs': recent_activities,  # Alias for template compatibility
            'campaign_status': campaign_status,
            'recent_campaigns': recent_campaigns,
            'top_channels': top_channels,
            'chart_data': chart_data,
        }
        
        return dashboard_data
     
     
@login_required
def dashboard_stats_api(request):
    """API endpoint for dashboard statistics."""
    # Get date range from request
    days = int(request.GET.get('days', 30))
    end_date = timezone.now()
    start_date = end_date - timedelta(days=days)
    
    # Campaign statistics over time
    campaigns_data = []
    for i in range(days):
        date = start_date + timedelta(days=i)
        count = Campaign.objects.filter(
            created_at__date=date.date(),
            is_deleted=False
        ).count()
        campaigns_data.append({
            'date': date.strftime('%Y-%m-%d'),
            'count': count
        })
    
    # Advertiser distribution
    advertiser_data = list(
        Advertiser.objects.filter(is_deleted=False)
        .annotate(campaign_count=Count('campaigns'))
        .values('name', 'campaign_count')
        .order_by('-campaign_count')[:10]
    )
    
    return JsonResponse({
        'campaigns_over_time': campaigns_data,
        'advertiser_distribution': advertiser_data,
    })


@login_required
def activity_logs(request):
    """View for displaying activity logs."""
    logs = ActivityLog.objects.select_related('user').order_by('-created_at')
    
    # Filter by action if provided
    action_filter = request.GET.get('action')
    if action_filter:
        logs = logs.filter(action=action_filter)
    
    # Filter by user if provided
    user_filter = request.GET.get('user')
    if user_filter:
        logs = logs.filter(user_id=user_filter)
    
    # Pagination
    from django.core.paginator import Paginator
    paginator = Paginator(logs, 50)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'action_choices': ActivityLog.ACTION_CHOICES,
    }
    
    return render(request, 'core/activity_logs.html', context)


def health_check_v1(request):
    """Health check endpoint for monitoring."""
    try:
        # Check database connection 
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
        
        # Check Redis connection (if using Celery)
        try:
            from django_redis import get_redis_connection
            redis_conn = get_redis_connection("default")
            redis_conn.ping()
            redis_status = "OK"
        except Exception:
            redis_status = "ERROR"
        
        return JsonResponse({
            'status': 'OK',
            'timestamp': timezone.now().isoformat(),
            'database': 'OK',
            'redis': redis_status,
        })
    except Exception as e:
        return JsonResponse({
            'status': 'ERROR',
            'error': str(e),
            'timestamp': timezone.now().isoformat(),
        }, status=500)


def health_check_v2(request):
    """Comprehensive health check endpoint"""
    health_status = {
        'status': 'healthy',
        'timestamp': datetime.now().isoformat(),
        'version': getattr(settings, 'VERSION', '1.0.0'),
        'checks': {}
    }
    
    overall_healthy = True
    
    # Database health check
    try:
        start_time = time.time()
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
            cursor.fetchone()
        db_response_time = round((time.time() - start_time) * 1000, 2)
        
        health_status['checks']['database'] = {
            'status': 'healthy',
            'response_time_ms': db_response_time
        }
    except Exception as e:
        health_status['checks']['database'] = {
            'status': 'unhealthy',
            'error': str(e)
        }
        overall_healthy = False
    
    # Redis health check
    try:
        start_time = time.time()
        cache.set('health_check', 'ok', 10)
        cache.get('health_check')
        redis_response_time = round((time.time() - start_time) * 1000, 2)
        
        health_status['checks']['redis'] = {
            'status': 'healthy',
            'response_time_ms': redis_response_time
        }
    except Exception as e:
        health_status['checks']['redis'] = {
            'status': 'unhealthy',
            'error': str(e)
        }
        overall_healthy = False
    
    # Celery health check (optional)
    try:
        from celery import current_app
        inspect = current_app.control.inspect()
        stats = inspect.stats()
        
        if stats:
            health_status['checks']['celery'] = {
                'status': 'healthy',
                'workers': len(stats)
            }
        else:
            health_status['checks']['celery'] = {
                'status': 'unhealthy',
                'error': 'No workers available'
            }
            overall_healthy = False
    except Exception as e:
        health_status['checks']['celery'] = {
            'status': 'unhealthy',
            'error': str(e)
        }
        # Don't mark overall as unhealthy for Celery issues
    
    # Set overall status
    if not overall_healthy:
        health_status['status'] = 'unhealthy'
    
    # Return appropriate HTTP status code
    status_code = 200 if overall_healthy else 503
    
    return JsonResponse(health_status, status=status_code)


def readiness_check(request):
    """Readiness check for Kubernetes/container orchestration"""
    try:
        # Check if database is ready
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
            cursor.fetchone()
        
        # Check if Redis is ready
        cache.set('readiness_check', 'ok', 10)
        cache.get('readiness_check')
        
        return JsonResponse({'status': 'ready'}, status=200)
    except Exception as e:
        return JsonResponse({
            'status': 'not_ready',
            'error': str(e)
        }, status=503)


def liveness_check(request):
    """Liveness check for Kubernetes/container orchestration"""
    return JsonResponse({
        'status': 'alive',
        'timestamp': datetime.now().isoformat()
    }, status=200)


# Error Views
class Error404View(TemplateView):
    """
    Custom 404 error page view.
    
    Displays a user-friendly 404 error page with navigation options.
    """
    
    template_name = "errors/404.html"
    
    def get_context_data(self, **kwargs):
        """
        Add 404 error context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        """
        context = super().get_context_data(**kwargs)
        
        context.update({
            "error_code": "404",
            "error_title": _("Page Not Found"),
            "error_message": _("The page you are looking for does not exist."),
            "suggestions": [
                {"text": _("Go to Homepage"), "url": reverse("core:landing")},
                {"text": _("Go to Dashboard"), "url": reverse("core:dashboard")},
                {"text": _("Contact Support"), "url": reverse("core:contact")}
            ]
        })
        
        return context


class Error500View(TemplateView):
    """
    Custom 500 error page view.
    
    Displays a user-friendly 500 error page with support information.
    """
    
    template_name = "errors/500.html"
    
    def get_context_data(self, **kwargs):
        """
        Add 500 error context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        """
        context = super().get_context_data(**kwargs)
        
        context.update({
            "error_code": "500",
            "error_title": _("Internal Server Error"),
            "error_message": _("Something went wrong on our end. Please try again later."),
            "support_email": "contact@adtlas.tv"
        })
        
        return context


class Error403View(TemplateView):
    """
    Custom 403 error page view.
    
    Displays a user-friendly 403 error page for permission denied.
    """
    
    template_name = "errors/403.html"
    
    def get_context_data(self, **kwargs):
        """
        Add 403 error context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        """
        context = super().get_context_data(**kwargs)
        
        context.update({
            "error_code": "403",
            "error_title": _("Access Forbidden"),
            "error_message": _("You do not have permission to access this resource."),
        })
        
        return context


class Error400View(TemplateView):
    """
    Custom 400 error page view.
    
    Displays a user-friendly 403 error page for permission denied.
    """
    
    template_name = "errors/400.html"
    
    def get_context_data(self, **kwargs):
        """
        Add 400 error context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        """
        context = super().get_context_data(**kwargs)
        
        context.update({
            "error_code": "400",
            "error_title": _("Bad Request"),
            "error_message": _("The request could not be understood by the server."),
        })
        
        return context


@method_decorator(cache_page(60 * 15), name="dispatch")  # Cache for 15 minutes
class HealthCheckView(View):
    """
    Health check endpoint for monitoring.
    
    Returns application health status and basic metrics.
    """
    
    def get(self, request):
        """
        Handle GET request for health check.
        
        Args:
            request: HTTP request object
            
        Returns:
            JsonResponse: Health check data
        """
        try:
            # Check database connectivity
            user_count = User.objects.count()
            
            # Check cache connectivity
            cache_key = "health_check_test"
            cache.set(cache_key, "test", 60)
            cache_test = cache.get(cache_key)
            
            health_data = {
                "status": "healthy",
                "timestamp": timezone.now().isoformat(),
                "database": "connected",
                "cache": "connected" if cache_test == "test" else "disconnected",
                "user_count": user_count,
                "version": getattr(settings, "APP_VERSION", "1.0.0")
            }
            
            return JsonResponse(health_data)
        
        except Exception as e:
            logger.error(f"Health check failed: {e}")
            return JsonResponse({
                "status": "unhealthy",
                "error": str(e),
                "timestamp": timezone.now().isoformat()
            }, status=500)


# ============================================================================
# Error Views
# ============================================================================

# Utility Functions
def handler404(request, exception):
    """
    Custom 404 error handler.
    
    Args:
        request: HTTP request object
        exception: Exception that caused 404
        
    Returns:
        HttpResponse: 404 error page
    """
    # Check if the request is an AJAX request
    if is_ajax_request(request):
        return JsonResponse({
            'success': False,
            'type': 'error',
            'message': _('Page not found'),
            'title': 'Not Found'
        }, status=404)
    # render 404 page
    return render(request, "errors/404.html", status=404)


def handler500(request):
    """
    Custom 500 error handler.
    
    Args:
        request: HTTP request object
        
    Returns:
        HttpResponse: 500 error page
    """
    # Check if the request is an AJAX request
    if is_ajax_request(request):
        return JsonResponse({
            'success': False,
            'type': 'error',
            'message': _('Internal server error'),
            'title': 'Server Error'
        }, status=500)
    # render 500 page
    return render(request, "errors/500.html", status=500)


def handler403(request, exception):
    """
    Custom 403 error handler.
    
    Args:
        request: HTTP request object
        exception: Exception that caused 403
        
    Returns:
        HttpResponse: 403 error page
    """
    # Check if the request is an AJAX request
    if is_ajax_request(request):
        return JsonResponse({
            'success': False,
            'type': 'error',
            'message': _('Forbidden'),
            'title': 'Access Denied'
        }, status=403)
    # render 403 page
    return render(request, "errors/403.html", status=403)


def handler400(request, exception):
    """
    Custom 400 error handler.
    
    Args:
        request: HTTP request object
        exception: Exception that caused 400
        
    Returns:
        HttpResponse: 400 error page
    """
    # Check if the request is an AJAX request
    if is_ajax_request(request):
        return JsonResponse({
            'success': False,
            'type': 'error',
            'message': _('Bad request'),
            'title': 'Bad Request'
        }, status=400)
    # render 400 page
    return render(request, "errors/400.html", status=400)
