from django.utils.translation import get_language
from django.shortcuts import redirect
from django.urls import reverse
from django.contrib import messages
from django.utils.translation import gettext as _
import logging

logger = logging.getLogger(__name__)

class LanguageDebugMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        # Log the current language for debugging
        # print(f"DEBUG: Path: {request.path}, Lang: {get_language()}, Cookie: {request.COOKIES.get('django_language')}")
        return response

class SubscriptionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Whitelisted paths that are always accessible
        whitelisted_paths = [
            reverse('logout'),
            reverse('login'),
            reverse('register'),
            reverse('verify_otp_registration'),
            reverse('verify_otp_login'),
            reverse('subscription_expired'),
            reverse('renew_subscription'),
            reverse('thawani_success'),
            reverse('thawani_cancel'),
            reverse('thawani_webhook'),
            reverse('home'),
            '/admin/',
            '/static/',
            '/media/',
            '/i18n/',
            '/receipt/', # Whitelist receipts so they can be viewed/printed
        ]
        
        # Check if the current path starts with any whitelisted path
        is_whitelisted = any(request.path.startswith(path) for path in whitelisted_paths)

        if request.user.is_authenticated and not request.user.is_superuser:
            try:
                profile = request.user.profile
                # Admins are exempted
                if profile.role == 'ADMIN':
                    return self.get_response(request)

                if profile.is_expired() and not is_whitelisted:
                    # Only redirect if they are not already on a whitelisted page
                    return redirect('subscription_expired')
            except Exception as e:
                logger.error(f"SubscriptionMiddleware error: {e}")

        response = self.get_response(request)
        return response