import uuid
from django.db import models
from django.utils import timezone

class Company(models.Model):
    COMPANY_SIZE_CHOICES = [
        ('1-5', '1-5 employees'),
        ('5-20', '5-20 employees'),
        ('20-50', '20-50 employees'),
        ('50-100', '50-100 employees'),
        ('100+', '100+ employees'),
    ]
    
    INDUSTRY_CHOICES = [
        ('construction', 'Construction'),
        ('technology', 'Technology'),
        ('healthcare', 'Healthcare'),
        ('retail', 'Retail'),
        ('manufacturing', 'Manufacturing'),
        ('services', 'Services'),
        ('other', 'Other'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=255)
    industry = models.CharField(max_length=50, choices=INDUSTRY_CHOICES)
    company_size = models.CharField(max_length=10, choices=COMPANY_SIZE_CHOICES)
    primary_location = models.CharField(max_length=255)
    operating_countries = models.JSONField(default=list)  # List of country codes
    api_endpoint = models.URLField(
        max_length=500,
        blank=True,
        null=True,
        help_text="API endpoint URL for user authentication (e.g., https://api.example.com/auth/login)"
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return self.name
    
    class Meta:
        ordering = ['-created_at']

class CollectiveAgreement(models.Model):
    AGREEMENT_TYPE_CHOICES = [
        ('rakennusalan_tes', 'Rakennusalan työehtosopimus (Construction)'),
        ('kvtes', 'KVTES (Municipal workers)'),
        ('avaintes', 'AVAINTES (Healthcare & social services)'),
        ('teknologiateollisuuden_tes', 'Teknologiateollisuuden TES (Technology)'),
        ('palvelualojen_tes', 'Palvelualojen TES (Service sector)'),
        ('kaupan_alan_tes', 'Kaupan alan TES (Retail)'),
        ('byggnads', 'Byggnads (Swedish Construction)'),
        ('other', 'Other / Custom'),
        ('none', 'No collective agreement (use Työaikalaki only)'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.OneToOneField(Company, on_delete=models.CASCADE, related_name='collective_agreement')
    agreement_type = models.CharField(max_length=50, choices=AGREEMENT_TYPE_CHOICES)
    custom_name = models.CharField(max_length=255, blank=True, null=True)
    organization = models.CharField(max_length=255, blank=True, null=True)
    overtime_2h_rate = models.DecimalField(max_digits=5, decimal_places=2, default=50.00)  # +50%
    overtime_after_2h_rate = models.DecimalField(max_digits=5, decimal_places=2, default=100.00)  # +100%
    night_work_rate = models.DecimalField(max_digits=5, decimal_places=2, default=30.00)  # +30%
    night_work_start = models.TimeField(default='22:00:00')
    night_work_end = models.TimeField(default='07:00:00')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return f"{self.company.name} - {self.get_agreement_type_display()}"
    
    class Meta:
        ordering = ['-created_at']

class WorkingTimePolicy(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='working_time_policies')
    name = models.CharField(max_length=255, help_text="Policy name (e.g., 'Standard 8-16', 'Flexible Hours')")
    description = models.TextField(blank=True, null=True, help_text="Optional description of the policy")
    created_by = models.ForeignKey('user.User', on_delete=models.SET_NULL, null=True, blank=True, related_name='created_working_time_policies')
    
    # Standard working hours
    monday_friday_start = models.TimeField(default='08:00:00')
    monday_friday_end = models.TimeField(default='16:00:00')

    #Weekend working hours
    saturday_start =models.TimeField(default='10:00:00')
    saturday_end = models.TimeField(default='15:00:00')

    sunday_start =models.TimeField(default='10:00:00')
    sunday_end = models.TimeField(default='15:00:00')
    # Flextime settings
    use_flextime = models.BooleanField(default=False)
    core_hours_start = models.TimeField(default='10:00:00')
    core_hours_end = models.TimeField(default='14:00:00')
    flex_range_start = models.TimeField(default='06:00:00')
    flex_range_end = models.TimeField(default='20:00:00')
    max_flex_negative = models.IntegerField(default=-10)  # hours
    max_flex_positive = models.IntegerField(default=40)  # hours
    
    # Working time banking
    use_time_banking = models.BooleanField(default=False)
    max_bank_balance = models.IntegerField(default=80)  # hours
    overtime_conversion_daily = models.IntegerField(default=8)  # hours
    overtime_conversion_weekly = models.IntegerField(default=40)  # hours
    
    # Lunch break policy
    lunch_break_paid = models.BooleanField(default=True)
    lunch_break_duration = models.IntegerField(default=30)  # minutes
    lunch_break_required_after = models.IntegerField(default=6)  # hours
    
    # Short break policy
    short_break_required = models.BooleanField(default=True)
    short_break_duration_minutes = models.IntegerField(default=15)
    short_break_required_after_hours = models.FloatField(default=4.0)  # Require break after 4h work
    minimum_total_break_time_minutes = models.IntegerField(default=45)
    
    # Burnout monitoring
    enable_violation_monitoring = models.BooleanField(default=False)
    violation_notification_enabled = models.BooleanField(default=False)
    monitor_daily_violations = models.BooleanField(default=False)
    monitor_weekly_violations = models.BooleanField(default=False)
    monitor_monthly_violations = models.BooleanField(default=False)
    monitor_missing_breaks = models.BooleanField(default=True)
    violation_severity_warning_threshold = models.FloatField(default=1.0)  # hours
    violation_severity_critical_threshold = models.FloatField(default=2.0)  # hours
    
    # Burnout detection
    burnout_detection_enabled = models.BooleanField(default=True)
    burnout_notification_enabled = models.BooleanField(default=True)
    burnout_sensitivity = models.CharField(
        max_length=20,
        choices=[('low', 'Low'), ('medium', 'Medium'), ('high', 'High')],
        default='medium'
    )
    
    # Overtime rules
    overtime_weekends_rate = models.DecimalField(max_digits=5, decimal_places=2, default=100.00)  # +100%
    overtime_holidays_rate = models.DecimalField(max_digits=5, decimal_places=2, default=100.00)  # +100%
    require_manager_approval = models.BooleanField(default=True)
    workers_self_register_overtime = models.BooleanField(default=False)
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return f"{self.name} - {self.company.name}"
    
    class Meta:
        ordering = ['-created_at']
        verbose_name_plural = 'Working Time Policies'

class VacationPolicy(models.Model):
    VACATION_ACCRUAL_CHOICES = [
        ('standard_finnish', 'Standard Finnish law (2 days/month, 2.5 after 1yr)'),
        ('custom', 'Custom accrual rate'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.OneToOneField(Company, on_delete=models.CASCADE, related_name='vacation_policy')
    
    # Vacation accrual
    vacation_accrual_type = models.CharField(max_length=20, choices=VACATION_ACCRUAL_CHOICES, default='standard_finnish')
    custom_accrual_rate = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)  # days per month
    
    # Vacation year
    vacation_year_start = models.DateField(default=timezone.now)
    vacation_period_start = models.DateField()
    vacation_period_end = models.DateField()
    
    # Balance tracking
    track_vacation_days = models.BooleanField(default=True)
    track_flex_time = models.BooleanField(default=True)
    track_time_bank = models.BooleanField(default=True)
    track_overtime_balance = models.BooleanField(default=True)
    track_toil = models.BooleanField(default=False)
    
    # Sick leave policy
    self_certification_days = models.IntegerField(default=3)
    sick_pay_percentage = models.IntegerField(default=100)
    
    # Public holidays
    include_finnish_holidays = models.BooleanField(default=True)
    include_swedish_holidays = models.BooleanField(default=False)
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return f"Vacation Policy - {self.company.name}"
    
    class Meta:
        ordering = ['-created_at']

class OnboardingProgress(models.Model):
    STEPS = [
        ('company_profile', 'Company Profile'),
        ('collective_agreement', 'Collective Agreement'),
        ('working_time_policy', 'Working Time Policy'),
        ('vacation_policy', 'Vacation Policy'),
        ('completed', 'Completed'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.OneToOneField(Company, on_delete=models.CASCADE, related_name='onboarding_progress')
    current_step = models.CharField(max_length=30, choices=STEPS, default='company_profile')
    is_completed = models.BooleanField(default=False)
    completed_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return f"Onboarding Progress - {self.company.name} ({self.current_step})"
    
    class Meta:
        ordering = ['-created_at']