import secrets

from django.db import models


class Client(models.Model):
    TIER_CHOICES = [
        ('platinum', 'Platinum'),
        ('gold',     'Gold'),
        ('silver',   'Silver'),
        ('bronze',   'Bronze'),
    ]

    name = models.CharField(max_length=200)
    code = models.CharField(max_length=20, unique=True)
    industry = models.CharField(max_length=100, blank=True)
    address = models.TextField(blank=True)
    website = models.URLField(blank=True)
    logo = models.ImageField(upload_to='client_logos/', null=True, blank=True)
    tier = models.CharField(max_length=10, choices=TIER_CHOICES, default='bronze')
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class ClientContact(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='contacts')
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=100, blank=True)
    email = models.EmailField()
    phone = models.CharField(max_length=20, blank=True)
    is_primary = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.name} - {self.client.name}"


class ClientDepartment(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='departments')
    name = models.CharField(max_length=100)
    code = models.CharField(max_length=20)
    description = models.TextField(blank=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.client.name} - {self.name}"


class TicketCategory(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='ticket_categories')
    name = models.CharField(max_length=100)
    code = models.CharField(max_length=20)
    description = models.TextField(blank=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.client.name} - {self.name}"

    class Meta:
        verbose_name_plural = 'Ticket Categories'


class TicketSubCategory(models.Model):
    category = models.ForeignKey(TicketCategory, on_delete=models.CASCADE, related_name='sub_categories')
    name = models.CharField(max_length=100)
    code = models.CharField(max_length=20)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.category.name} - {self.name}"

    class Meta:
        verbose_name_plural = 'Ticket Sub Categories'


class ClientConfiguration(models.Model):
    client = models.OneToOneField(Client, on_delete=models.CASCADE, related_name='configuration')

    # VICIdial
    vicidial_server    = models.CharField(max_length=200, blank=True)
    vicidial_port      = models.CharField(max_length=10, blank=True, default='8080')
    vicidial_user      = models.CharField(max_length=100, blank=True)
    vicidial_pass      = models.CharField(max_length=200, blank=True)
    vicidial_api_user  = models.CharField(max_length=100, blank=True)
    vicidial_api_pass  = models.CharField(max_length=200, blank=True)
    vicidial_campaigns = models.CharField(max_length=500, blank=True, help_text='Comma-separated campaign IDs')
    vicidial_ingroup   = models.CharField(max_length=200, blank=True, help_text='Inbound group names')

    # pfSense / Network
    pfsense_wan_ip     = models.CharField(max_length=50, blank=True)
    pfsense_lan_subnet = models.CharField(max_length=50, blank=True)
    pfsense_admin_url  = models.CharField(max_length=200, blank=True)
    pfsense_vpn_type   = models.CharField(max_length=20, blank=True, choices=[('openvpn','OpenVPN'),('ipsec','IPSec'),('wireguard','WireGuard'),('none','None')])
    pfsense_vpn_notes  = models.TextField(blank=True)
    pfsense_notes      = models.TextField(blank=True)

    # Starlink
    starlink_ip        = models.CharField(max_length=50, blank=True, default='192.168.100.1')
    starlink_notes     = models.TextField(blank=True)

    # Extra ping targets (comma-separated IPs or hostnames)
    network_ping_targets = models.CharField(max_length=500, blank=True, help_text='Comma-separated IPs to monitor')
    # Per-client daily speed-test report
    report_emails        = models.TextField(blank=True, default='', help_text='Recipients of this client\'s daily speed report')
    speedtest_requested  = models.BooleanField(default=False, help_text='On-demand "Speed Test Now" flag for this client')
    # Stamped every time this client's pfSense probe polls for pending work.
    # "Speed Test Now" only raises a flag — without a probe polling for it,
    # nothing ever runs, and the UI used to claim success regardless.
    probe_last_seen      = models.DateTimeField(null=True, blank=True,
                                                help_text='Last time this client\'s pfSense probe checked in')

    # Social Media
    facebook_page      = models.CharField(max_length=200, blank=True)
    facebook_page_id   = models.CharField(max_length=100, blank=True)
    twitter_handle     = models.CharField(max_length=100, blank=True)
    instagram_handle   = models.CharField(max_length=100, blank=True)
    linkedin_page      = models.CharField(max_length=200, blank=True)
    whatsapp_number    = models.CharField(max_length=30, blank=True)
    youtube_channel    = models.CharField(max_length=200, blank=True)
    tiktok_handle      = models.CharField(max_length=100, blank=True)

    # PinkTool DB connection
    pinktool_db_host   = models.CharField(max_length=200, blank=True, default='127.0.0.1')
    pinktool_db_port   = models.CharField(max_length=10,  blank=True, default='3306')
    pinktool_db_name   = models.CharField(max_length=100, blank=True)
    pinktool_db_user   = models.CharField(max_length=100, blank=True)
    pinktool_db_pass   = models.CharField(max_length=200, blank=True)

    # General / Other
    timezone           = models.CharField(max_length=60, blank=True, default='UTC')
    support_email      = models.EmailField(blank=True)
    escalation_email   = models.EmailField(blank=True)
    billing_email      = models.EmailField(blank=True)
    webhook_url        = models.CharField(max_length=500, blank=True)
    custom_domain      = models.CharField(max_length=200, blank=True)
    crm_notes          = models.TextField(blank=True)

    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"Config – {self.client.name}"

    class Meta:
        verbose_name = 'Client Configuration'


class ClientNetwork(models.Model):
    ISP_CHOICES = [
        ('globe',   'Globe'),
        ('pldt',    'PLDT'),
        ('dito',    'Dito'),
        ('converge','Converge'),
        ('sky',     'Sky'),
        ('starlink','Starlink'),
        ('other',   'Other'),
    ]
    client              = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='networks')
    name                = models.CharField(max_length=100, help_text='e.g. Globe Main, PLDT Backup')
    isp                 = models.CharField(max_length=20, choices=ISP_CHOICES, default='other')
    # --- basic connection: everything needed to add a link, whatever it runs ---
    # The static IP the provider assigned. Reachability checks use this; the
    # older pfsense_wan_ip is kept as a fallback for connections added before.
    static_ip           = models.CharField(max_length=50, blank=True, default='',
                                           help_text='Static IP from the provider')
    ssh_port            = models.CharField(max_length=10, blank=True, default='',
                                           help_text='Port used to reach it, e.g. 22')

    # --- optional pfSense sync, filled in after the connection exists ---
    # pfSense's own name for this line's gateway, e.g. WANPLDTGW. It is how
    # incoming telemetry is matched to this network: speed tests and outage
    # alerts arrive labelled by gateway, and without this they all pile onto
    # whichever network happens to be primary.
    gateway_name        = models.CharField(max_length=120, blank=True, default='',
                                           help_text='pfSense gateway name, e.g. WANPLDTGW')
    pfsense_wan_ip      = models.CharField(max_length=50, blank=True)
    pfsense_admin_url   = models.CharField(max_length=200, blank=True)
    pfsense_lan_subnet  = models.CharField(max_length=50, blank=True)
    # Legacy. Defaulted to 192.168.100.1, which auto-populated on every new
    # connection and then reported a permanent false DOWN — the CRM cannot reach
    # a private address. No longer collected, displayed, or pinged; a real
    # Starlink address belongs in the Ping field.
    starlink_ip         = models.CharField(max_length=50, blank=True, default='')
    extra_ping_targets  = models.CharField(max_length=500, blank=True)
    notes               = models.TextField(blank=True)
    is_primary          = models.BooleanField(default=False)
    # Turn monitoring off without losing the connection or its history — a line
    # being decommissioned, or one that is down for planned work and shouldn't
    # be generating alerts.
    is_active           = models.BooleanField(default=True)
    # Last-seen up/down per public target, so the server-side monitor can alert
    # only on state *changes* (e.g. {"203.0.113.5": "up"}).
    last_status         = models.JSONField(default=dict, blank=True)
    # Identifies THIS network when its on-premise pfSense posts an alert, so the
    # ticket lands on the right client instead of whichever client happens to be
    # first in the database. Baked into the install script served per network.
    monitor_key         = models.CharField(max_length=48, unique=True, blank=True, default='',
                                           help_text='Auto-generated. Identifies this pfSense to the CRM.')
    created_at          = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        if not self.monitor_key:
            self.monitor_key = secrets.token_urlsafe(24)[:48]
        return super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.client.name} – {self.name}"

    class Meta:
        ordering = ['-is_primary', 'name']


def network_for_gateway(client_id, gateway):
    """Which ClientNetwork does this pfSense gateway belong to?

    Telemetry arrives labelled by gateway name (WANPLDTGW), so an explicit
    ``gateway_name`` on the network is the reliable match. Falls back to the
    primary network — better a coarse grouping than dropping the reading — and
    the label on each row still says which gateway it came from.
    """
    qs = ClientNetwork.objects.filter(client_id=client_id)
    gw = (gateway or '').strip()
    if gw:
        # An explicit name wins even if the line is switched off — telemetry
        # that does arrive should still be filed where it belongs.
        match = qs.filter(gateway_name__iexact=gw).first()
        if match:
            return match
    active = qs.filter(is_active=True)
    return (active.filter(is_primary=True).first() or active.first()
            or qs.filter(is_primary=True).first() or qs.first())


class NetworkAlert(models.Model):
    """A gateway going down or recovering, as reported by that site's pfSense.

    These used to be filed as tickets, which buried real customer tickets under
    infrastructure noise — a flapping WAN could produce dozens a day. They live
    here instead and are shown on the network's own card in Configuration, the
    same way an email account shows its own state.
    """
    DOWN = 'down'
    UP = 'up'
    KIND_CHOICES = [(DOWN, 'Down'), (UP, 'Recovered')]

    client     = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='network_alerts')
    network    = models.ForeignKey(ClientNetwork, on_delete=models.SET_NULL, null=True, blank=True,
                                   related_name='alerts')
    kind       = models.CharField(max_length=8, choices=KIND_CHOICES, db_index=True)
    gateway    = models.CharField(max_length=120, blank=True, default='')
    message    = models.CharField(max_length=500, blank=True, default='')
    detail     = models.TextField(blank=True, default='')
    # Set when the matching recovery arrives, so an outage has a duration.
    resolved_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ['-created_at']
        indexes = [models.Index(fields=['client', '-created_at'])]

    def __str__(self):
        return f'{self.get_kind_display()} {self.gateway} @ {self.created_at:%Y-%m-%d %H:%M}'


class NetworkSpeedTest(models.Model):
    """One speed-test run pushed by pfSense (the nightly report, or on demand)."""
    client     = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='speed_tests')
    network    = models.ForeignKey(ClientNetwork, on_delete=models.SET_NULL, null=True, blank=True,
                                   related_name='speed_tests')
    gateway    = models.CharField(max_length=120, blank=True, default='')
    # Null when the gateway was down and the test was skipped.
    mbps       = models.FloatField(null=True, blank=True)
    raw        = models.TextField(blank=True, default='')
    tested_at  = models.DateTimeField(db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-tested_at']
        indexes = [models.Index(fields=['client', '-tested_at'])]

    def __str__(self):
        return f'{self.gateway}: {self.mbps or "n/a"} Mbps @ {self.tested_at:%Y-%m-%d}'


class ClientDatabase(models.Model):
    client   = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='databases')
    name     = models.CharField(max_length=100)
    host     = models.CharField(max_length=200, default='127.0.0.1')
    port     = models.CharField(max_length=10, default='3306')
    db_name  = models.CharField(max_length=100)
    db_user  = models.CharField(max_length=100, blank=True)
    db_pass  = models.CharField(max_length=200, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.client.name} – {self.name}"

    class Meta:
        ordering = ['name']


class ClientEmailAccount(models.Model):
    client          = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='email_accounts')
    name            = models.CharField(max_length=100)
    email           = models.EmailField()
    assigned_agent  = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True, blank=True, related_name='assigned_email_accounts')
    # IMAP (incoming)
    imap_host   = models.CharField(max_length=200, default='')
    imap_port   = models.CharField(max_length=10, default='993')
    imap_user   = models.CharField(max_length=200, blank=True)
    imap_pass   = models.CharField(max_length=200, blank=True)
    imap_ssl    = models.BooleanField(default=True)
    imap_folder = models.CharField(max_length=100, default='INBOX')
    # Freshdesk-style ingestion state — track the highest processed IMAP UID
    # instead of relying on the \Seen flag (which webmail/other clients flip).
    last_uid          = models.BigIntegerField(default=0)
    imap_uidvalidity  = models.CharField(max_length=50, blank=True, default='')
    # SMTP (outgoing)
    smtp_host   = models.CharField(max_length=200, default='')
    smtp_port   = models.CharField(max_length=10, default='587')
    smtp_user   = models.CharField(max_length=200, blank=True)
    smtp_pass   = models.CharField(max_length=200, blank=True)
    smtp_tls    = models.BooleanField(default=True)
    is_active   = models.BooleanField(default=True)
    created_at  = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.client.name} – {self.name} <{self.email}>"

    class Meta:
        ordering = ['name']


class ClientEscalationMatrix(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='escalation_matrix')
    level = models.IntegerField()
    role = models.CharField(max_length=50)
    user = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True, blank=True)
    email = models.EmailField(blank=True)
    notify_after_minutes = models.IntegerField(default=60)

    class Meta:
        ordering = ['level']


class OutboundEmail(models.Model):
    """One email an agent composed and sent from a client mailbox.

    Ticket replies are already logged as TicketComment rows. This covers the
    other direction — mail an agent starts themselves, which previously had no
    home in the CRM at all and so left no record of who emailed a customer,
    from which mailbox, or what was said.

    Kept even when sending fails: a failed row is how the agent finds out why,
    and how an admin later sees that an attempt was made.
    """
    QUEUED = 'queued'
    SENT   = 'sent'
    FAILED = 'failed'
    STATUS_CHOICES = [(QUEUED, 'Queued'), (SENT, 'Sent'), (FAILED, 'Failed')]

    client      = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='outbound_emails')
    account     = models.ForeignKey(ClientEmailAccount, on_delete=models.SET_NULL,
                                   null=True, blank=True, related_name='outbound_emails')
    sender      = models.ForeignKey('core.User', on_delete=models.SET_NULL,
                                    null=True, blank=True, related_name='sent_outbound_emails')
    to_emails   = models.TextField()
    cc_emails   = models.TextField(blank=True, default='')
    subject     = models.CharField(max_length=500)
    body        = models.TextField()
    # Set when the draft came from the AI helper, so we can tell later how much
    # customer-facing mail was AI-assisted versus written from scratch.
    ai_assisted = models.BooleanField(default=False)
    status      = models.CharField(max_length=10, choices=STATUS_CHOICES, default=QUEUED)
    message_id  = models.CharField(max_length=300, blank=True, default='')
    error       = models.TextField(blank=True, default='')
    ticket      = models.ForeignKey('tickets.Ticket', on_delete=models.SET_NULL,
                                   null=True, blank=True, related_name='outbound_emails')
    created_at  = models.DateTimeField(auto_now_add=True)
    sent_at     = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['-created_at']
        indexes = [models.Index(fields=['client', '-created_at'])]

    def __str__(self):
        return f'{self.subject} -> {self.to_emails} ({self.status})'
