"""Outbound follow-up email: Gmail API (OAuth) preferred, SMTP fallback."""

from __future__ import annotations

import smtplib
import ssl
from email.message import EmailMessage
from email.utils import formataddr

from sqlalchemy.orm import Session

from app.agent.templates import render_follow_up_email
from app.config import settings
from app.gmail_oauth import (
    GmailAuthError,
    GmailSendError,
    resolve_send_account,
    send_message as gmail_send_message,
)
from app.models import EmailLog, FollowUp, Lead
from app.services import mark_follow_up


class EmailSendError(Exception):
    """Raised when outbound send fails."""


def _from_address(lead: Lead) -> str:
    return (lead.our_email or settings.smtp_from or settings.smtp_user or "").strip()


def preview_follow_up_email(lead: Lead, fu_number: int) -> dict:
    rendered = render_follow_up_email(lead, fu_number)
    return {
        "lead_id": lead.id,
        "lead_code": lead.lead_code,
        "contact_name": lead.contact_name,
        "follow_up_number": fu_number,
        "to": lead.client_email,
        "from_address": _from_address(lead),
        "subject": rendered["subject"],
        "text": rendered["text"],
        "html": rendered["html"],
        "day_label": rendered["day_label"],
        "goal": rendered["goal"],
        "email_type": rendered["email_type"],
        "will_mark_done": True,
    }


def _smtp_send(msg: EmailMessage) -> None:
    if not settings.smtp_configured:
        raise EmailSendError(
            "SMTP is not configured. Set SMTP_HOST and SMTP_FROM (or SMTP_USER) in .env"
        )

    host = settings.smtp_host
    port = settings.smtp_port
    user = settings.smtp_user or None
    password = settings.smtp_password or None

    try:
        if settings.smtp_use_tls:
            context = ssl.create_default_context()
            with smtplib.SMTP(host, port, timeout=30) as server:
                server.ehlo()
                server.starttls(context=context)
                server.ehlo()
                if user and password:
                    server.login(user, password)
                server.send_message(msg)
        else:
            with smtplib.SMTP(host, port, timeout=30) as server:
                if user and password:
                    server.login(user, password)
                server.send_message(msg)
    except Exception as exc:  # noqa: BLE001 — surface any SMTP failure
        raise EmailSendError(str(exc)) from exc


def _deliver(db: Session, from_addr: str, msg: EmailMessage) -> str:
    """Send via Gmail OAuth and/or SMTP per EMAIL_PROVIDER. Returns provider label."""
    provider = (settings.email_provider or "auto").strip().lower()

    if provider not in {"auto", "gmail", "smtp"}:
        raise EmailSendError(
            f"Invalid EMAIL_PROVIDER={provider!r}; use auto, gmail, or smtp"
        )

    if provider in {"auto", "gmail"}:
        account = resolve_send_account(db, from_addr)
        if account:
            # Prefer exact match; if from_addr set but different account resolved as default,
            # require match when from_addr is explicit and account email differs.
            if from_addr and account.email.lower() != from_addr.lower():
                if provider == "gmail":
                    raise EmailSendError(
                        f"No Gmail OAuth connection for {from_addr}. "
                        "Connect that mailbox under Gmail accounts, or clear Our Email "
                        "to use the default connected account."
                    )
                # auto: fall through to SMTP
            else:
                # Align From with the authorized mailbox
                if not from_addr:
                    msg.replace_header("From", formataddr((account.email.split("@")[0], account.email)))
                try:
                    gmail_send_message(db, account, msg)
                    return f"gmail:{account.email}"
                except (GmailSendError, GmailAuthError) as exc:
                    if provider == "gmail":
                        raise EmailSendError(str(exc)) from exc
                    # auto: try SMTP next
                    pass
        elif provider == "gmail":
            raise EmailSendError(
                "No Gmail accounts connected. Open Gmail accounts → Connect Gmail, "
                "or set EMAIL_PROVIDER=smtp to use SMTP."
            )

    if provider in {"auto", "smtp"}:
        if settings.smtp_configured:
            _smtp_send(msg)
            return "smtp"
        if provider == "smtp":
            raise EmailSendError(
                "SMTP is not configured. Set SMTP_* in .env or switch to Gmail OAuth."
            )

    raise EmailSendError(
        f"Cannot send from {from_addr or '(default)'}: connect that Gmail account "
        "via OAuth, or configure SMTP as a fallback."
    )


def send_follow_up_email(
    db: Session,
    lead: Lead,
    fu_number: int,
    *,
    dry_run: bool = False,
    transcript_snippet: str | None = None,
    mark_done: bool = True,
) -> dict:
    """Send FU email (or preview). Marks FU done only after successful send."""
    fu = next((f for f in lead.follow_ups if f.number == fu_number), None)
    if not fu:
        raise ValueError(f"Follow-up {fu_number} not found for lead {lead.lead_code}")

    preview = preview_follow_up_email(lead, fu_number)
    if dry_run:
        return {**preview, "dry_run": True, "status": "planned"}

    from_addr = preview["from_address"]
    # Allow empty from when a default Gmail account exists
    if not from_addr and not resolve_send_account(db, None):
        raise EmailSendError(
            "No from address: set lead Our Email, connect a default Gmail account, "
            "or set SMTP_FROM"
        )
    if not lead.client_email:
        raise EmailSendError("Lead has no client_email")

    # Resolve display From (may be filled by default Gmail account)
    send_from = from_addr
    if not send_from:
        account = resolve_send_account(db, None)
        send_from = account.email if account else ""

    msg = EmailMessage()
    msg["Subject"] = preview["subject"]
    msg["From"] = formataddr((send_from.split("@")[0], send_from))
    msg["To"] = lead.client_email
    msg.set_content(preview["text"])
    msg.add_alternative(preview["html"], subtype="html")

    try:
        provider = _deliver(db, send_from, msg)
    except EmailSendError as exc:
        log = EmailLog(
            lead_id=lead.id,
            follow_up_number=fu_number,
            to_address=lead.client_email,
            from_address=send_from or from_addr,
            subject=preview["subject"],
            status="failed",
            error=str(exc),
            transcript_snippet=(transcript_snippet or "")[:500] or None,
        )
        db.add(log)
        db.commit()
        raise

    log = EmailLog(
        lead_id=lead.id,
        follow_up_number=fu_number,
        to_address=lead.client_email,
        from_address=send_from or from_addr,
        subject=preview["subject"],
        status="sent",
        error=None,
        transcript_snippet=(transcript_snippet or "")[:500] or None,
    )
    db.add(log)

    # Always mark this FU done after a successful send (re-fetch in case session expired)
    if mark_done:
        fu_row = (
            db.query(FollowUp)
            .filter(FollowUp.lead_id == lead.id, FollowUp.number == fu_number)
            .one_or_none()
        ) or fu
        if fu_row.status != "done":
            mark_follow_up(fu_row, "done")
        fu = fu_row

    db.commit()
    db.refresh(fu)

    return {
        **preview,
        "from_address": send_from or from_addr,
        "dry_run": False,
        "status": "sent",
        "provider": provider,
        "email_log_id": log.id,
        "follow_up_status": fu.status,
        "will_mark_done": True,
        "marked_done": mark_done and fu.status == "done",
    }


def next_pending_follow_up(lead: Lead) -> FollowUp | None:
    pending = sorted(
        [fu for fu in lead.follow_ups if fu.status == "pending"],
        key=lambda f: f.number,
    )
    return pending[0] if pending else None


def list_email_logs(db: Session, *, limit: int = 50) -> list[EmailLog]:
    return (
        db.query(EmailLog)
        .order_by(EmailLog.created_at.desc())
        .limit(limit)
        .all()
    )
