import uuid
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils import timezone


class Role(models.Model):
    SYSTEM_ADMIN = 'system_admin'
    CLIENT_ADMIN = 'client_admin'
    OPERATIONS_MANAGER = 'operations_manager'
    TEAM_LEADER = 'team_leader'
    AGENT = 'agent'
    QA_ANALYST = 'qa_analyst'
    CLIENT_REVIEWER = 'client_reviewer'
    APPROVER = 'approver'
    FINANCE_USER = 'finance_user'
    REPORTING_USER = 'reporting_user'
    READ_ONLY = 'read_only'

    ROLE_CHOICES = [
        (SYSTEM_ADMIN, 'System Administrator'),
        (CLIENT_ADMIN, 'Client Administrator'),
        (OPERATIONS_MANAGER, 'Operations Manager'),
        (TEAM_LEADER, 'Team Leader'),
        (AGENT, 'Agent'),
        (QA_ANALYST, 'QA Analyst'),
        (CLIENT_REVIEWER, 'Client Reviewer'),
        (APPROVER, 'Approver'),
        (FINANCE_USER, 'Finance User'),
        (REPORTING_USER, 'Reporting User'),
        (READ_ONLY, 'Read-only User'),
    ]

    name = models.CharField(max_length=50, choices=ROLE_CHOICES, unique=True)
    display_name = models.CharField(max_length=100)
    permissions = models.JSONField(default=dict)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.display_name


class User(AbstractUser):
    role = models.ForeignKey(Role, on_delete=models.SET_NULL, null=True, blank=True)
    client = models.ForeignKey('clients.Client', on_delete=models.SET_NULL, null=True, blank=True)
    department = models.CharField(max_length=100, blank=True)
    phone = models.CharField(max_length=20, blank=True)
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)
    two_factor_enabled = models.BooleanField(default=False)
    last_login_ip = models.GenericIPAddressField(null=True, blank=True)
    vicidial_user = models.CharField(max_length=20, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.get_full_name()} ({self.username})"

    def has_permission(self, perm):
        if self.is_superuser:
            return True
        if self.role and self.role.permissions:
            return self.role.permissions.get(perm, False)
        return False


class SystemConfig(models.Model):
    """Singleton table for system-wide configuration."""
    PROVIDER_CHOICES = [
        ('anthropic', 'Anthropic (Claude)'),
        ('gemini',    'Google Gemini'),
        ('groq',      'Groq'),
        ('openai',    'OpenAI'),
        ('ollama',    'Ollama (Local)'),
    ]
    ai_enabled   = models.BooleanField(default=False)
    ai_provider  = models.CharField(max_length=20, choices=PROVIDER_CHOICES, default='gemini')
    ai_model     = models.CharField(max_length=100, default='gemini-1.5-flash')
    ai_api_key   = models.CharField(max_length=500, blank=True, default='')
    ai_base_url  = models.CharField(max_length=300, blank=True, default='')
    ai_keys      = models.JSONField(default=dict, blank=True)  # per-provider keys
    # AI auto-reply agent for inbound email. When enabled and the AI's confidence
    # meets the threshold, replies are sent automatically; below it they are
    # drafted for an agent. Set threshold to 101 for draft-only (never auto-send).
    autoreply_enabled    = models.BooleanField(default=False)
    autoreply_confidence = models.IntegerField(default=85)
    # Recipients for the daily network speed-test report (comma-separated).
    report_emails = models.TextField(blank=True, default='')
    # On-demand "Speed Test Now": set true by the button, cleared when pfSense polls.
    speedtest_requested = models.BooleanField(default=False)
    updated_at   = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'System Configuration'

    @classmethod
    def get(cls):
        obj, _ = cls.objects.get_or_create(pk=1)
        return obj


class JobRun(models.Model):
    """Last-known state of each scheduled job.

    Everything periodic in this system runs as an external cron hitting a URL,
    with nothing watching it. Two outages have already come from that: queued AI
    replies sat unsent for days, and the nightly speed report vanished for
    three — both silent, both found by a human noticing an absence.

    One row per job, overwritten each run, so the admin can see at a glance when
    each last succeeded and whether it is overdue.
    """
    OK = 'ok'
    FAILED = 'failed'
    STATUS_CHOICES = [(OK, 'OK'), (FAILED, 'Failed')]

    name        = models.CharField(max_length=60, unique=True)
    status      = models.CharField(max_length=10, choices=STATUS_CHOICES, default=OK)
    last_run_at = models.DateTimeField(null=True, blank=True)
    last_ok_at  = models.DateTimeField(null=True, blank=True)
    detail      = models.CharField(max_length=500, blank=True, default='')
    error       = models.TextField(blank=True, default='')
    run_count   = models.PositiveIntegerField(default=0)
    fail_count  = models.PositiveIntegerField(default=0)
    # Flag the job as overdue after this long without a success.
    expected_every_minutes = models.PositiveIntegerField(default=15)

    class Meta:
        ordering = ['name']

    def __str__(self):
        return f'{self.name}: {self.status}'

    @property
    def is_overdue(self):
        from django.utils import timezone
        from datetime import timedelta
        if not self.last_ok_at:
            return True
        return timezone.now() - self.last_ok_at > timedelta(minutes=self.expected_every_minutes * 2)


class LoginHistory(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='login_history')
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    user_agent = models.TextField(blank=True)
    success = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']


class ClientInvitation(models.Model):
    token      = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
    client     = models.ForeignKey('clients.Client', on_delete=models.CASCADE, related_name='invitations')
    email      = models.EmailField()
    invited_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='sent_invitations')
    created_at = models.DateTimeField(auto_now_add=True)
    expires_at = models.DateTimeField()
    used_at    = models.DateTimeField(null=True, blank=True)
    is_used    = models.BooleanField(default=False)

    def is_valid(self):
        return not self.is_used and timezone.now() < self.expires_at

    def __str__(self):
        return f"Invite → {self.email} ({self.client.name})"

    class Meta:
        ordering = ['-created_at']
