"""
Debug script to check why notifications weren't sent for a user
Run: python manage.py shell < debug_notification.py
Or: python manage.py shell, then copy-paste the code
"""
import os
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'worktimeapp.settings')
django.setup()

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, timedelta
import pytz

USER_ID = "edd631c63c1848c681244f5c7c868801"

print("=" * 80)
print(f"DEBUGGING NOTIFICATIONS FOR USER: {USER_ID}")
print("=" * 80)
print()

# 1. Check UserPattern records
print("1. CHECKING USER PATTERNS")
print("-" * 80)
patterns = UserPattern.objects.filter(user_id=USER_ID)
if patterns.exists():
    print(f"✓ Found {patterns.count()} pattern(s):")
    for pattern in patterns:
        print(f"  - question_type: {pattern.question_type}")
        print(f"    average_time: {pattern.average_time}")
        print(f"    confidence_score: {pattern.confidence_score}")
        print(f"    sample_size: {pattern.sample_size}")
        print(f"    last_updated: {pattern.last_updated}")
        print()
else:
    print("✗ NO PATTERNS FOUND - This is likely the problem!")
    print("  User needs at least 3 stamps per question_type to learn patterns.")
    print()

# 2. Check UserSettings (timezone)
print("2. CHECKING USER SETTINGS (TIMEZONE)")
print("-" * 80)
try:
    user_settings = UserSettings.objects.get(user_id=USER_ID)
    print(f"✓ User timezone: {user_settings.user_timezone}")
    user_tz = pytz.timezone(user_settings.user_timezone)
    now_user_tz = timezone.now().astimezone(user_tz)
    print(f"  Current time in user timezone: {now_user_tz.strftime('%Y-%m-%d %H:%M:%S %Z')}")
except UserSettings.DoesNotExist:
    print("✗ NO USER SETTINGS FOUND - Defaulting to UTC")
    print("  This could cause timezone issues!")
    user_tz = pytz.UTC
    now_user_tz = timezone.now().astimezone(user_tz)
print()

# 3. Check ScheduledNotification records for today
print("3. CHECKING SCHEDULED NOTIFICATIONS FOR TODAY")
print("-" * 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():
    print(f"✓ Found {scheduled_today.count()} scheduled notification(s) for today:")
    for notif in scheduled_today:
        print(f"  - question_type: {notif.question_type}")
        print(f"    scheduled_time: {notif.scheduled_time}")
        print(f"    is_sent: {notif.is_sent}")
        print(f"    sent_at: {notif.sent_at}")
        print(f"    celery_task_id: {notif.celery_task_id}")
        if notif.notification_title:
            print(f"    title: {notif.notification_title}")
        print()
else:
    print("✗ NO SCHEDULED NOTIFICATIONS FOR TODAY")
    print("  This means schedule_daily_notifications() either:")
    print("  - Didn't run today")
    print("  - Ran but found no patterns")
    print("  - Ran but all notifications were skipped")
    print()

# 4. Check if user already made stamps today
print("4. CHECKING IF USER ALREADY MADE STAMPS TODAY")
print("-" * 80)
if patterns.exists():
    push_service = PushNotificationService()
    for pattern in patterns:
        function = Function.objects.filter(question_type=pattern.question_type).first()
        if function:
            # Check if stamp exists today
            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():
                print(f"✓ User already made {pattern.question_type} stamp(s) today:")
                for stamp in stamps_today:
                    print(f"  - Time: {stamp.time}, Date: {stamp.date}")
            else:
                print(f"✗ User has NOT made {pattern.question_type} stamp today")
                
            # Check with time comparison
            already_did = push_service.user_already_did_action_at_time(
                USER_ID, 
                pattern.question_type, 
                pattern.average_time
            )
            print(f"  user_already_did_action_at_time({pattern.average_time}): {already_did}")
            print()
else:
    print("Skipping - no patterns to check")
    print()

# 5. Check FCM token
print("5. CHECKING FCM TOKEN")
print("-" * 80)
try:
    from ml_service.models import UserFCMToken
    fcm_tokens = UserFCMToken.objects.filter(user_id=USER_ID, is_active=True)
    if fcm_tokens.exists():
        print(f"✓ Found {fcm_tokens.count()} active FCM token(s):")
        for token in fcm_tokens:
            print(f"  - Token: {token.token[:50]}...")
            print(f"    device_type: {token.device_type}")
            print(f"    created_at: {token.created_at}")
    else:
        print("✗ NO ACTIVE FCM TOKEN FOUND")
        print("  User needs to register FCM token in the app!")
except Exception as e:
    print(f"✗ Error checking FCM tokens: {e}")
print()

# 6. Check what would happen if we scheduled now
print("6. SIMULATING SCHEDULING LOGIC")
print("-" * 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)
        )
        
        print(f"For {pattern.question_type} (average_time: {typical_time}):")
        print(f"  Notification datetime (user tz): {notification_datetime_user_tz}")
        print(f"  Current time (user tz): {now_user_tz}")
        
        if notification_datetime_user_tz <= now_user_tz:
            print(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:
                print(f"  ✗ User already made stamp - notification would be SKIPPED")
            else:
                print(f"  ✓ User hasn't made stamp - notification SHOULD BE SENT")
        else:
            print(f"  ✗ Average time has NOT PASSED yet - notification would be scheduled for later")
        print()
else:
    print("Skipping - no patterns to simulate")
    print()

# 7. Summary
print("=" * 80)
print("SUMMARY")
print("=" * 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:
    print("ISSUES FOUND:")
    for issue in issues:
        print(f"  {issue}")
else:
    print("✓ All checks passed - notifications should work")
    print("  If notifications still don't send, check:")
    print("  - Celery worker is running")
    print("  - Celery Beat is running (for scheduled tasks)")
    print("  - Firebase service account is configured")

print()
print("=" * 80)

