"""
AI auto-reply agent for inbound email tickets.

Flow when enabled (SystemConfig.autoreply_enabled):
  1. Skip automated / no-reply senders (DMARC reports, newsletters, bounces).
  2. Ask the AI to name the customer's concern and draft a human reply.
  3. Draft-only mode (confidence threshold set to 101) -> post an internal note.
     Otherwise -> QUEUE the reply to send 5-10 minutes later (human-like delay),
     from a real agent, with a clean body (no AI/metadata text).
  4. A periodic sweep (send_due_replies, called by the email watcher) sends any
     queued replies whose time has come.

Safe by design: no AI configured -> no-op; never replies to automated senders;
never invents order numbers/amounts.
"""
import json
import random
import re
from datetime import timedelta

from django.conf import settings
from django.utils import timezone


# Senders we must never auto-reply to (automated / no-reply / reports).
AUTOMATED_MARKERS = (
    'noreply', 'no-reply', 'donotreply', 'do-not-reply', 'mailer-daemon',
    'postmaster', 'dmarc', 'notification', 'notifications', 'bounce', 'mailer',
)
AUTOMATED_SUBJECT_MARKERS = ('report domain', 'report-id', 'dmarc', 'delivery status', 'daily network speed report')


def _extract_json(text):
    if not text:
        return None
    m = re.search(r'\{.*\}', text, re.DOTALL)
    if not m:
        return None
    try:
        return json.loads(m.group(0))
    except Exception:
        return None


def _first_name(name):
    n = (name or '').strip()
    return n.split()[0] if n and '@' not in n else 'there'


def _is_automated(ticket):
    email = (ticket.customer_email or '').lower()
    if not email:
        return True
    if any(m in email for m in AUTOMATED_MARKERS):
        return True
    subj = (ticket.subject or '').lower()
    if any(m in subj for m in AUTOMATED_SUBJECT_MARKERS):
        return True
    return False


def _send_ticket_email(ticket, subject, body):
    """Send a reply from the client's email account. Returns (ok, msgid_or_error).

    The From display name is always the email ACCOUNT name (e.g. "Beta test"),
    never the agent's — customers should see the support mailbox they wrote to.
    The handling agent is identified in the signature at the bottom of the body.
    """
    from clients.models import ClientEmailAccount
    acct = (
        ClientEmailAccount.objects.filter(client=ticket.client, is_active=True,
                                          name=ticket.channel_source).first()
        or ClientEmailAccount.objects.filter(client=ticket.client, is_active=True).first()
    )
    if not acct:
        return False, 'no active email account'
    to_email = ticket.customer_email
    if not to_email:
        return False, 'no recipient'

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.utils import make_msgid

    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = f'{acct.name} <{acct.email}>'
    msg['To'] = to_email
    msg['Reply-To'] = acct.email
    out_msgid = make_msgid(domain=(acct.email.split('@')[-1] or None))
    msg['Message-ID'] = out_msgid
    if ticket.source_message_id:
        msg['In-Reply-To'] = ticket.source_message_id
        msg['References'] = ticket.source_message_id
    html_body = body.replace('\n', '<br>')
    msg.attach(MIMEText(body, 'plain', 'utf-8'))
    msg.attach(MIMEText(
        f'<div style="font-family:sans-serif;font-size:14px;line-height:1.6">{html_body}</div>',
        'html', 'utf-8'))

    port = int(acct.smtp_port)
    if port == 465:
        server = smtplib.SMTP_SSL(acct.smtp_host, port, timeout=20)
    else:
        server = smtplib.SMTP(acct.smtp_host, port, timeout=20)
        if acct.smtp_tls:
            server.starttls()
    raw = msg.as_string()
    server.login(acct.smtp_user or acct.email, acct.smtp_pass)
    server.sendmail(acct.email, [to_email], raw)
    server.quit()

    # File a copy in the mailbox's Sent folder. SMTP alone never does this, so
    # without it the support mailbox shows incoming mail but no replies.
    from core.mailbox import save_to_sent
    save_to_sent(acct, raw)

    return True, out_msgid


def _conversation(ticket):
    """Full thread as a transcript so the AI can continue the conversation."""
    lines = [f"Customer: {(ticket.description or '').strip()[:2000]}"]
    for c in ticket.comments.order_by('created_at'):
        if c.comment_type in ('customer_reply', 'client_reply'):
            lines.append(f"Customer: {c.body.strip()[:1500]}")
        elif c.comment_type == 'public':
            lines.append(f"You (support): {c.body.strip()[:1500]}")
        # internal notes are omitted
    return "\n\n".join(lines)


TEAM_SIGNOFF = 'Customer Support Team'

# A queued reply this far past its send time is dropped rather than sent late.
STALE_AFTER_HOURS = 12


class ArchiveKind:
    """Mirrors AIReplyArchive's choices without importing models at module load."""
    SENT = 'sent'
    DRAFT = 'draft'


def archive_reply(ticket, body, kind, subject='', concern='', category='', tone='', agent=None):
    """Record an AI-written reply so agents can search and reuse it later.

    Never raises: archiving is a convenience, and losing it must not fail the
    send that just succeeded or the draft the agent is waiting on.
    """
    try:
        from ai_services.models import AIReplyArchive
        if not (body or '').strip() or not getattr(ticket, 'client_id', None):
            return None
        return AIReplyArchive.objects.create(
            client_id=ticket.client_id, ticket=ticket, kind=kind,
            subject=(subject or ticket.subject or '')[:500], body=body,
            concern=(concern or ticket.ai_summary or '')[:500],
            category=(category or ticket.ai_suggested_category or '')[:100],
            tone=tone[:40], agent=agent,
        )
    except Exception:
        return None


def _agent_signature(ticket):
    """Name the reply is signed with — the assigned agent, else the team."""
    ag = ticket.assigned_agent
    if ag and ag.is_active:
        return (ag.get_full_name() or '').strip() or ag.username
    return TEAM_SIGNOFF


def _build_prompt(ticket):
    from ai_services.reply_playbook import REPLY_PLAYBOOK
    company = ticket.client.name if ticket.client else 'our company'
    signer = _agent_signature(ticket)
    return f"""You are an experienced customer-support specialist at {company},
personally handling an ongoing email conversation with a customer. Write like a
real, friendly human — not a bot.

Use this reference playbook to decide the BEST way to handle the request, then
write a natural reply adapted to this customer and company. Follow its intent and
tone, but do not quote fees, amounts, or policies that aren't relevant, and never
invent specifics not in the customer's messages.

--- REFERENCE PLAYBOOK ---
{REPLY_PLAYBOOK}
--- END PLAYBOOK ---

Customer: {ticket.customer_name} <{ticket.customer_email}>
Subject: {ticket.subject}

CONVERSATION SO FAR (oldest first):
{_conversation(ticket)}

Write the NEXT reply to the customer's most recent message, taking the whole
conversation into account. Don't repeat what you've already said.

Return ONLY valid JSON (no markdown, no commentary):
{{
  "concern": "one sentence naming the customer's core concern or request",
  "category": "billing | technical | complaint | inquiry | refund | order | general",
  "confidence": 0-100,
  "reply": "the email reply text only"
}}

How to write the reply:
- Greet them by first name (e.g. "Hi {_first_name(ticket.customer_name)},").
- Warm, natural, conversational tone. Short paragraphs. Plain language.
- Directly acknowledge their specific concern, then help.
- No corporate stiffness, no robotic filler, no "As an AI". Never say you are an AI.
- Do NOT invent order numbers, tracking numbers, dates, or amounts. If a detail
  isn't in their email, speak generally or say you're looking into it.
- End with a friendly sign-off, then sign with the handling agent's name on its
  own line, exactly: {signer}
  Then a final line: Customer Support Team

confidence = how sure you are the reply fully and correctly resolves this WITHOUT a
human. Use a low number for refunds, payments, angry/complaint, legal, or ambiguous."""


def auto_reply_to_ticket(ticket):
    """Analyse a new email ticket and either queue an auto-reply or draft a note."""
    from ai_services.views import _claude_generate
    from ai_services.models import ScheduledReply
    from tickets.models import TicketComment

    if ticket.channel != 'email' or not ticket.customer_email:
        return {'action': 'skipped', 'reason': 'not_emailable'}

    enabled = getattr(settings, 'AI_AUTOREPLY_ENABLED', True)
    threshold = int(getattr(settings, 'AI_AUTOREPLY_CONFIDENCE', 85))
    try:
        from core.models import SystemConfig
        cfg = SystemConfig.get()
        enabled = cfg.autoreply_enabled
        threshold = cfg.autoreply_confidence
    except Exception:
        pass
    if not enabled:
        return {'action': 'skipped', 'reason': 'disabled'}
    if _is_automated(ticket):
        return {'action': 'skipped', 'reason': 'automated_sender'}

    data = _extract_json(_claude_generate(_build_prompt(ticket)))
    if not data or not str(data.get('reply', '')).strip():
        return {'action': 'skipped', 'reason': 'no_ai'}

    concern = str(data.get('concern', ''))[:500]
    reply = str(data.get('reply', '')).strip()
    # Safety net: the body must end with the handling agent's name followed by the
    # team line, even if the model skipped the sign-off instruction.
    signer = _agent_signature(ticket)
    if signer.lower() not in reply.lower():
        reply = f'{reply}\n\n{signer}'
    if TEAM_SIGNOFF.lower() not in reply.lower():
        reply = f'{reply}\n{TEAM_SIGNOFF}'
    try:
        confidence = int(data.get('confidence', 0))
    except Exception:
        confidence = 0

    ticket.ai_summary = concern
    ticket.ai_suggested_category = str(data.get('category', ''))[:100]
    ticket.save(update_fields=['ai_summary', 'ai_suggested_category'])

    # Only auto-send when the ticket has an ASSIGNED, active agent. Draft-only
    # mode, or an unassigned ticket, keeps the reply as an internal note.
    assigned = ticket.assigned_agent if (ticket.assigned_agent_id and ticket.assigned_agent
                                         and ticket.assigned_agent.is_active) else None
    if threshold >= 101 or not assigned:
        reason = 'draft-only mode' if threshold >= 101 else 'no agent assigned yet'
        TicketComment.objects.create(
            ticket=ticket, author=None, comment_type=TicketComment.INTERNAL, is_ai_generated=True,
            body=f'🤖 AI suggested reply ({reason}). Review & send.\nConcern: {concern}\n\n{reply}',
        )
        archive_reply(ticket, reply, ArchiveKind.DRAFT, concern=concern,
                      category=str(data.get('category', ''))[:100])
        return {'action': 'drafted', 'reason': reason, 'confidence': confidence, 'concern': concern}

    # Queue a human-like delayed auto-send from the assigned agent. If an earlier
    # reply is still pending (customer sent another message first), cancel it so
    # we answer the latest message with full context instead of double-replying.
    ScheduledReply.objects.filter(ticket=ticket, status=ScheduledReply.PENDING).update(
        status=ScheduledReply.CANCELLED)
    dmin = int(getattr(settings, 'AI_AUTOREPLY_DELAY_MIN', 5))
    dmax = int(getattr(settings, 'AI_AUTOREPLY_DELAY_MAX', 10))
    delay = random.randint(dmin * 60, max(dmin, dmax) * 60)
    ScheduledReply.objects.create(
        ticket=ticket, agent=assigned, subject=f'Re: {ticket.subject}', body=reply,
        send_at=timezone.now() + timedelta(seconds=delay),
    )
    return {'action': 'scheduled', 'confidence': confidence, 'send_in_min': round(delay / 60, 1),
            'agent': assigned.get_full_name() or assigned.username}


def send_due_replies():
    """Send any queued replies whose send_at has passed. Returns count sent.
    Called each cycle by the email watcher."""
    from ai_services.models import ScheduledReply
    from tickets.models import TicketComment

    # Staleness guard: a reply that is badly overdue (the sweep wasn't running,
    # the server was down, ...) is no longer a timely answer -- sending it would
    # blast old replies at customers all at once. Cancel those instead.
    stale_cutoff = timezone.now() - timedelta(hours=STALE_AFTER_HOURS)
    ScheduledReply.objects.filter(status=ScheduledReply.PENDING,
                                  send_at__lt=stale_cutoff).update(
        status=ScheduledReply.CANCELLED, error='cancelled: overdue, no longer timely')

    due = (ScheduledReply.objects
           .filter(status=ScheduledReply.PENDING, send_at__lte=timezone.now())
           .select_related('ticket', 'agent'))
    sent = 0
    for sr in due:
        ticket = sr.ticket
        try:
            ok, info = _send_ticket_email(ticket, sr.subject or f'Re: {ticket.subject}', sr.body)
        except Exception as e:
            ok, info = False, str(e)
        if ok:
            # Clean public reply, attributed to the real agent — no AI metadata.
            TicketComment.objects.create(
                ticket=ticket, author=sr.agent, comment_type=TicketComment.PUBLIC,
                is_ai_generated=True, source_message_id=info, body=sr.body,
            )
            uf = ['updated_at']
            if not ticket.first_responded_at:
                ticket.first_responded_at = timezone.now()
                uf.append('first_responded_at')
            ticket.save(update_fields=uf)
            sr.status = ScheduledReply.SENT
            sr.sent_at = timezone.now()
            sr.save(update_fields=['status', 'sent_at'])
            # Only replies that actually reached a customer are archived as
            # 'sent' — those are the ones worth reusing verbatim.
            archive_reply(ticket, sr.body, ArchiveKind.SENT,
                          subject=sr.subject, agent=sr.agent)
            sent += 1
        else:
            sr.status = ScheduledReply.FAILED
            sr.error = str(info)[:500]
            sr.save(update_fields=['status', 'error'])
    return sent
