from django.core.management.base import BaseCommand
from django.utils import timezone
from ml_service.models import UserPattern, ScheduledNotification
from userSettings.models import UserSettings
from stamps.models import Stamp
from functions.models import Function
from ml_service.push_service import PushNotificationService
from datetime import datetime
import pytz


class Command(BaseCommand):
    help = 'Debug why notifications were not sent for a specific user'

    def add_arguments(self, parser):
        parser.add_argument(
            '--user-id',
            type=str,
            required=True,
            help='User ID to debug',
        )

    def handle(self, *args, **options):
        user_id = options['user_id']
        
        self.stdout.write("=" * 80)
        self.stdout.write(f"DEBUGGING NOTIFICATIONS FOR USER: {user_id}")
        self.stdout.write("=" * 80)
        self.stdout.write("")
        
        # 1. Check UserPattern records
        self.stdout.write("1. CHECKING USER PATTERNS")
        self.stdout.write("-" * 80)
        patterns = UserPattern.objects.filter(user_id=user_id)
        if patterns.exists():
            self.stdout.write(self.style.SUCCESS(f"Found {patterns.count()} pattern(s):"))
            for pattern in patterns:
                self.stdout.write(f"  - question_type: {pattern.question_type}")
                self.stdout.write(f"    average_time: {pattern.average_time}")
                self.stdout.write(f"    confidence_score: {pattern.confidence_score}")
                self.stdout.write(f"    sample_size: {pattern.sample_size}")
                self.stdout.write(f"    last_updated: {pattern.last_updated}")
                self.stdout.write("")
        else:
            self.stdout.write(self.style.ERROR("NO PATTERNS FOUND - This is likely the problem!"))
            self.stdout.write("  User needs at least 3 stamps per question_type to learn patterns.")
            self.stdout.write("")
        
        # 2. Check UserSettings (timezone)
        self.stdout.write("2. CHECKING USER SETTINGS (TIMEZONE)")
        self.stdout.write("-" * 80)
        try:
            user_settings = UserSettings.objects.get(user_id=user_id)
            self.stdout.write(self.style.SUCCESS(f"User timezone: {user_settings.user_timezone}"))
            user_tz = pytz.timezone(user_settings.user_timezone)
            now_user_tz = timezone.now().astimezone(user_tz)
            self.stdout.write(f"  Current time in user timezone: {now_user_tz.strftime('%Y-%m-%d %H:%M:%S %Z')}")
        except UserSettings.DoesNotExist:
            self.stdout.write(self.style.ERROR("NO USER SETTINGS FOUND - Defaulting to UTC"))
            self.stdout.write("  This could cause timezone issues!")
            user_tz = pytz.UTC
            now_user_tz = timezone.now().astimezone(user_tz)
        self.stdout.write("")
        
        # 3. Check ScheduledNotification records for today
        self.stdout.write("3. CHECKING SCHEDULED NOTIFICATIONS FOR TODAY")
        self.stdout.write("-" * 80)
        today_utc = timezone.now().date()
        scheduled_today = ScheduledNotification.objects.filter(
            user_id=user_id,
            scheduled_time__date=today_utc
        ).order_by('-scheduled_time')
        
        if scheduled_today.exists():
            self.stdout.write(self.style.SUCCESS(f"Found {scheduled_today.count()} scheduled notification(s) for today:"))
            for notif in scheduled_today:
                self.stdout.write(f"  - question_type: {notif.question_type}")
                self.stdout.write(f"    scheduled_time: {notif.scheduled_time}")
                self.stdout.write(f"    is_sent: {notif.is_sent}")
                self.stdout.write(f"    sent_at: {notif.sent_at}")
                self.stdout.write(f"    celery_task_id: {notif.celery_task_id}")
                if notif.notification_title:
                    self.stdout.write(f"    title: {notif.notification_title}")
                self.stdout.write("")
        else:
            self.stdout.write(self.style.ERROR("NO SCHEDULED NOTIFICATIONS FOR TODAY"))
            self.stdout.write("  This means schedule_daily_notifications() either:")
            self.stdout.write("  - Didn't run today")
            self.stdout.write("  - Ran but found no patterns")
            self.stdout.write("  - Ran but all notifications were skipped")
            self.stdout.write("")
        
        # 4. Check if user already made stamps today
        self.stdout.write("4. CHECKING IF USER ALREADY MADE STAMPS TODAY")
        self.stdout.write("-" * 80)
        if patterns.exists():
            push_service = PushNotificationService()
            for pattern in patterns:
                function = Function.objects.filter(question_type=pattern.question_type).first()
                if function:
                    today_user_tz = now_user_tz.date()
                    stamps_today = Stamp.objects.filter(
                        user__id=user_id,
                        stamp_function=function.function_ref_id,
                        date=today_user_tz
                    )
                    
                    if stamps_today.exists():
                        self.stdout.write(self.style.SUCCESS(f"User already made {pattern.question_type} stamp(s) today:"))
                        for stamp in stamps_today:
                            self.stdout.write(f"  - Time: {stamp.time}, Date: {stamp.date}")
                    else:
                        self.stdout.write(self.style.WARNING(f"User has NOT made {pattern.question_type} stamp today"))
                    
                    already_did = push_service.user_already_did_action_at_time(
                        user_id, 
                        pattern.question_type, 
                        pattern.average_time
                    )
                    status = "YES" if already_did else "NO"
                    self.stdout.write(f"  user_already_did_action_at_time({pattern.average_time}): {status}")
                    self.stdout.write("")
        else:
            self.stdout.write("Skipping - no patterns to check")
            self.stdout.write("")
        
        # 5. Check FCM token
        self.stdout.write("5. CHECKING FCM TOKEN")
        self.stdout.write("-" * 80)
        try:
            from ml_service.models import UserFCMToken
            fcm_tokens = UserFCMToken.objects.filter(user_id=user_id, is_active=True)
            if fcm_tokens.exists():
                self.stdout.write(self.style.SUCCESS(f"Found {fcm_tokens.count()} active FCM token(s):"))
                for token in fcm_tokens:
                    self.stdout.write(f"  - Token: {token.token[:50]}...")
                    self.stdout.write(f"    device_type: {token.device_type}")
                    self.stdout.write(f"    created_at: {token.created_at}")
            else:
                self.stdout.write(self.style.ERROR("NO ACTIVE FCM TOKEN FOUND"))
                self.stdout.write("  User needs to register FCM token in the app!")
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"Error checking FCM tokens: {e}"))
        self.stdout.write("")
        
        # 6. Check what would happen if we scheduled now
        self.stdout.write("6. SIMULATING SCHEDULING LOGIC")
        self.stdout.write("-" * 80)
        if patterns.exists():
            for pattern in patterns:
                typical_time = pattern.average_time
                today_user_tz = now_user_tz.date()
                notification_datetime_user_tz = user_tz.localize(
                    datetime.combine(today_user_tz, typical_time)
                )
                
                self.stdout.write(f"For {pattern.question_type} (average_time: {typical_time}):")
                self.stdout.write(f"  Notification datetime (user tz): {notification_datetime_user_tz}")
                self.stdout.write(f"  Current time (user tz): {now_user_tz}")
                
                if notification_datetime_user_tz <= now_user_tz:
                    self.stdout.write(self.style.SUCCESS(f"  Average time has PASSED"))
                    push_service = PushNotificationService()
                    already_did = push_service.user_already_did_action_at_time(
                        user_id, 
                        pattern.question_type, 
                        typical_time
                    )
                    if already_did:
                        self.stdout.write(self.style.WARNING(f"  User already made stamp - notification would be SKIPPED"))
                    else:
                        self.stdout.write(self.style.SUCCESS(f"  User hasn't made stamp - notification SHOULD BE SENT"))
                else:
                    self.stdout.write(self.style.WARNING(f"  Average time has NOT PASSED yet - notification would be scheduled for later"))
                self.stdout.write("")
        else:
            self.stdout.write("Skipping - no patterns to simulate")
            self.stdout.write("")
        
        # 7. Summary
        self.stdout.write("=" * 80)
        self.stdout.write("SUMMARY")
        self.stdout.write("=" * 80)
        issues = []
        
        if not patterns.exists():
            issues.append("NO PATTERNS LEARNED - User needs at least 3 stamps per question_type")
        
        try:
            user_settings = UserSettings.objects.get(user_id=user_id)
        except UserSettings.DoesNotExist:
            issues.append("NO USER TIMEZONE SET - Using UTC (may cause time issues)")
        
        if not scheduled_today.exists():
            issues.append("NO NOTIFICATIONS SCHEDULED FOR TODAY - schedule_daily_notifications() may not have run")
        
        try:
            from ml_service.models import UserFCMToken
            if not UserFCMToken.objects.filter(user_id=user_id, is_active=True).exists():
                issues.append("NO FCM TOKEN REGISTERED - User needs to register token in app")
        except:
            pass
        
        if issues:
            self.stdout.write(self.style.ERROR("ISSUES FOUND:"))
            for issue in issues:
                self.stdout.write(f"  {issue}")
        else:
            self.stdout.write(self.style.SUCCESS("All checks passed - notifications should work"))
            self.stdout.write("  If notifications still don't send, check:")
            self.stdout.write("  - Celery worker is running")
            self.stdout.write("  - Celery Beat is running (for scheduled tasks)")
            self.stdout.write("  - Firebase service account is configured")
        
        self.stdout.write("")
        self.stdout.write("=" * 80)

