from django.shortcuts import redirect
from django.urls import reverse
from django.utils import timezone
from django.contrib import messages
from .models import Profile, SiteHit, CandidateWallet
from .utils import add_v_coins

class VideshChaloMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        path = request.path.lower()
        
        # 🛡️ 1. JUNK FILTERING
        ignored_ext = ['.ico', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.css', '.js', '.map', '.txt', '.xml']
        is_junk = any(path.endswith(ext) for ext in ignored_ext)
        is_admin = path.startswith('/admin/') or path.startswith('/secret-entry/') or path.startswith('/static/')
        
        if not is_junk and not is_admin:
            try:
                # 🛠️ SESSION BASED UNIQUE TRACKING
                is_unique_visit = False
                if not request.session.get('videsh_chalo_session_active'):
                    is_unique_visit = True
                    request.session['videsh_chalo_session_active'] = True
                    request.session.set_expiry(1800) # 30 min timeout

                SiteHit.objects.create(
                    path=request.path,
                    is_unique=is_unique_visit
                )
            except:
                pass

        # 🔗 2. REFERRAL TRACKING
        ref_id = request.GET.get('ref')
        if ref_id: 
            request.session['referrer_id'] = ref_id

        # 🛡️ 3. ROLE SELECTION & AUTH LOGIC
        if request.user.is_authenticated and not request.user.is_superuser:
            # A. Check Role Completion
            if not getattr(request.user, 'is_candidate', False) and not getattr(request.user, 'is_recruiter', False):
                allowed = [reverse('home'), reverse('account_logout'), reverse('set_user_role'), 
                           reverse('candidate_register'), reverse('recruiter_register')]
                if request.path not in allowed and not request.path.startswith('/static/'):
                    return redirect('home')

            # 🔥 B. NAYA: DAILY LOGIN REWARD LOGIC
            # Ye har page load par check hoga, par reward din mein sirf ek baar milega
            if getattr(request.user, 'is_candidate', False):
                try:
                    today = timezone.localdate()
                    # Wallet fetch ya create karein
                    coin_wallet, _ = CandidateWallet.objects.get_or_create(user=request.user)

                    if coin_wallet.last_login_reward != today:
                        # 10 V-Coins credit karo
                        add_v_coins(request.user, 10, "Daily Login Reward")
                        
                        # Wallet refresh aur date update taaki aaj dobara na mile
                        coin_wallet.refresh_from_db()
                        coin_wallet.last_login_reward = today
                        coin_wallet.save()
                        
                        # Pop-up message jo user ko kisi bhi page par dikhega
                        messages.success(request, "Login bonus for today: 10 V-Coins added to your wallet! 🎉")
                except Exception as e:
                    # Background mein error print karein par user ko na dikhayein
                    print(f"Login Reward Error: {e}")

        # 🚀 4. GET RESPONSE (View execution)
        response = self.get_response(request)
        
        # ⏱️ 5. POST-RESPONSE: LAST SEEN UPDATE
        if hasattr(request, 'user') and request.user.is_authenticated:
            try:
                Profile.objects.filter(user=request.user).update(last_seen=timezone.now())
            except:
                pass

        return response