"""
Test script to trigger compliance notifications and send them to your phone
Run this to receive test compliance alerts
"""

import os
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'worktimeapp.settings')
django.setup()

import sys
from datetime import datetime, timedelta, time
from django.utils import timezone
from stamps.models import Stamp
from user.models import User
from company.compliance_checker import ComplianceChecker
from ml_service.push_service import PushNotificationService
from functions.models import Function

def create_test_stamps_for_compliance():
    """Create stamps that would trigger compliance violations"""
    
    # Get test user
    user_id = '575f8050-e027-4db9-9ff1-31e0b1b7dfad'
    
    try:
        user = User.objects.get(id=user_id)
        print(f"[OK] Found user: {user.firstname} {user.lastname}")
        
        # Check if compliance is enabled
        if not user.compliance_enabled:
            print("[WARN] Compliance monitoring is disabled for this user")
            print("Enable it in the app settings first!")
            return
        
        print("[OK] Compliance monitoring is enabled")
        
    except User.DoesNotExist:
        print(f"[ERROR] User not found: {user_id}")
        return
    
    # Get today
    today = timezone.now().date()
    
    # Get function IDs
    try:
        clock_in = Function.objects.filter(question_type='clock_in').first()
        clock_out = Function.objects.filter(question_type='clock_out').first()
        lunch_out = Function.objects.filter(question_type='lunch_out').first()
        lunch_in = Function.objects.filter(question_type='lunch_in').first()
        
        if not clock_in or not clock_out:
            print("[ERROR] Clock in/out functions not found")
            return
        
        print("[OK] Found functions")
        
    except Exception as e:
        print(f"[ERROR] Error getting functions: {e}")
        return
    
    # Check existing stamps today
    existing_stamps = Stamp.objects.filter(user_id=user_id, date=today)
    
    if existing_stamps.exists():
        print(f"\n[WARN] {existing_stamps.count()} stamps already exist for today")
        response = input("Delete existing stamps and create new test scenario? (y/n): ")
        if response.lower() == 'y':
            existing_stamps.delete()
            print("[OK] Deleted existing stamps")
        else:
            print("Keeping existing stamps, analyzing current state...")
    
    # Create ComplianceChecker
    checker = ComplianceChecker(user_id=user_id)
    
    # Check current compliance
    print("\nChecking current compliance status...")
    alerts = checker.check_compliance()
    
    if alerts:
        print(f"\n[ALERT] Found {len(alerts)} compliance alerts:")
        for alert in alerts:
            print(f"\n  Type: {alert['type']}")
            print(f"  Severity: {alert['severity']}")
            print(f"  Message: {alert['message']}")
            if alert.get('time_remaining'):
                print(f"  Time remaining: {alert['time_remaining']:.1f} hours")
    else:
        print("\n[OK] No compliance issues found")
    
    # Send notifications
    if alerts:
        print("\nSending compliance notifications...")
        push_service = PushNotificationService()
        
        for alert in alerts:
            # Determine title based on severity
            if alert['severity'] == 'critical':
                title = "🚨 Critical Compliance Alert"
                emoji = "🚨"
            elif alert['severity'] == 'high':
                title = "⚠️ Compliance Warning"
                emoji = "⚠️"
            else:
                title = "💡 Compliance Reminder"
                emoji = "💡"
            
            # Add emoji to message
            body = f"{emoji} {alert['message']}"
            
            # Send notification
            success = push_service.send_notification(
                user_id,
                title=title,
                body=body,
                data={
                    'type': 'compliance_alert',
                    'alert_type': alert['type'],
                    'severity': alert['severity'],
                    'notification_type': 'compliance'
                }
            )
            
            if success:
                print(f"[OK] Sent: {alert['severity'].upper()} - {alert['message'][:50]}...")
            else:
                print(f"[ERROR] Failed to send: {alert['message'][:50]}...")
    
    print("\n" + "="*50)
    print("Test Complete!")
    print("="*50)

if __name__ == '__main__':
    print("="*50)
    print("COMPLIANCE NOTIFICATION TEST")
    print("="*50)
    print("\nThis script will:")
    print("1. Check user's compliance status")
    print("2. Generate compliance alerts based on current work patterns")
    print("3. Send push notifications to your phone")
    print("\nNote: You must have FCM token registered first!")
    print("="*50 + "\n")
    
    create_test_stamps_for_compliance()

