"""
Create test stamps that will trigger compliance violations
This will make the user work for 8+ hours without breaks
"""

import os
import django

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

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

def create_violation_scenario():
    """Create stamps that violate compliance rules"""
    
    user_id = '575f8050-e027-4db9-9ff1-31e0b1b7dfad'
    today = timezone.now().date()
    
    # Check user and compliance
    try:
        user = User.objects.get(id=user_id)
        print(f"User: {user.firstname} {user.lastname}")
        print(f"Compliance enabled: {user.compliance_enabled}")
        
        if not user.compliance_enabled:
            print("\n[WARN] Compliance is disabled! Enable it in the app first.")
            enable = input("Enable compliance for this user? (y/n): ")
            if enable.lower() == 'y':
                user.compliance_enabled = True
                user.save()
                print("[OK] Compliance enabled")
        
    except User.DoesNotExist:
        print(f"[ERROR] User not found: {user_id}")
        return
    
    # Get functions
    clock_in = Function.objects.filter(question_type='clock_in').first()
    clock_out = Function.objects.filter(question_type='clock_out').first()
    
    if not clock_in or not clock_out:
        print("[ERROR] Functions not found")
        return
    
    # Delete existing stamps for today
    Stamp.objects.filter(user_id=user_id, date=today).delete()
    print("[OK] Deleted existing stamps for today")
    
    # Create excessive work scenario - 8.5 hours with no breaks!
    print("\nCreating violation scenario: 8.5 hours with no breaks...")
    
    start_time = time(8, 0)  # 8:00 AM
    end_time = time(16, 30)  # 4:30 PM (8.5 hours)
    
    # Combine date and time
    start_datetime = timezone.make_aware(datetime.combine(today, start_time))
    end_datetime = timezone.make_aware(datetime.combine(today, end_time))
    
    # Create clock in
    clock_in_stamp = Stamp.objects.create(
        user=user,
        date=today,
        time=start_time,
        stamp_function=clock_in.id,
        start_date=start_datetime,
        description="Test clock in"
    )
    print(f"[OK] Clock in at {start_time}")
    
    # Create clock out (no lunch, no breaks)
    clock_out_stamp = Stamp.objects.create(
        user=user,
        date=today,
        time=end_time,
        stamp_function=clock_out.id,
        start_date=end_datetime,
        description="Test clock out"
    )
    print(f"[OK] Clock out at {end_time}")
    
    print(f"\n[OK] Created scenario: {start_time} to {end_time} (8.5 hours, no breaks)")
    
    # Now check compliance
    print("\nChecking compliance...")
    checker = ComplianceChecker(user_id=user_id)
    alerts = checker.check_compliance()
    
    if alerts:
        print(f"\n[ALERT] {len(alerts)} compliance violation(s) detected:")
        for i, alert in enumerate(alerts, 1):
            print(f"\n{i}. {alert['severity'].upper()}: {alert['message']}")
            if alert.get('time_remaining'):
                print(f"   Time remaining: {alert['time_remaining']:.1f} hours")
        
        # Send push notifications
        print("\nSending push notifications...")
        push_service = PushNotificationService()
        
        for alert in alerts:
            if alert['severity'] == 'critical':
                title = "Critical Compliance Alert"
                emoji = "🚨"
            elif alert['severity'] == 'high':
                title = "Compliance Warning"
                emoji = "⚠️"
            else:
                title = "Compliance Reminder"
                emoji = "💡"
            
            body = f"{emoji} {alert['message']}"
            
            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: {title}")
            else:
                print(f"[ERROR] Failed to send")
    else:
        print("\n[OK] No compliance violations detected")
    
    print("\n" + "="*60)
    print("Test scenario complete!")
    print("Check your phone for notifications")
    print("="*60)

if __name__ == '__main__':
    create_violation_scenario()

