"""Inbound mail automation API: rules, status, run, events."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from app.database import get_db
from app.gmail_oauth import GmailAuthError
from app.inbound_mail import (
    classify_message,
    get_or_create_rules,
    get_poll_status,
    list_events,
    rules_to_dict,
    run_inbound_poll,
    run_live_self_test,
    update_rules,
)
from app.schemas import (
    InboundMailEventOut,
    InboundMailRulesOut,
    InboundMailRulesUpdate,
    InboundMailRunOut,
    InboundMailSelfTestOut,
    InboundMailStatusOut,
    InboundMailTestClassifyIn,
    InboundMailTestClassifyOut,
)

router = APIRouter(prefix="/api/inbound-mail", tags=["inbound-mail"])


@router.get("/rules", response_model=InboundMailRulesOut)
def get_rules(db: Session = Depends(get_db)):
    row = get_or_create_rules(db)
    return InboundMailRulesOut(**rules_to_dict(row))


@router.put("/rules", response_model=InboundMailRulesOut)
def put_rules(payload: InboundMailRulesUpdate, db: Session = Depends(get_db)):
    row = update_rules(
        db,
        enabled=payload.enabled,
        filter_keywords=payload.filter_keywords,
        positive_keywords=payload.positive_keywords,
        negative_keywords=payload.negative_keywords,
        poll_interval_seconds=payload.poll_interval_seconds,
    )
    return InboundMailRulesOut(**rules_to_dict(row))


@router.get("/status", response_model=InboundMailStatusOut)
def status(db: Session = Depends(get_db)):
    return InboundMailStatusOut(**get_poll_status(db))


@router.post("/run", response_model=InboundMailRunOut)
def run_now(db: Session = Depends(get_db)):
    try:
        result = run_inbound_poll(db, force=True)
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(502, f"Inbound poll failed: {exc}") from exc
    return InboundMailRunOut(**result)


@router.post("/test-classify", response_model=InboundMailTestClassifyOut)
def test_classify(payload: InboundMailTestClassifyIn, db: Session = Depends(get_db)):
    """Dry-run classifier against current keyword rules (no Gmail / no lead create)."""
    rules = rules_to_dict(get_or_create_rules(db))
    result = classify_message(
        subject=payload.subject or "",
        body=payload.body or "",
        filter_keywords=rules["filter_keywords"],
        positive_keywords=rules["positive_keywords"],
        negative_keywords=rules["negative_keywords"],
        from_email=payload.from_email or "",
        from_name=payload.from_name or "",
    )
    classification = result["classification"]
    would_create = classification == "positive"
    notes = {
        "positive": "Would create a Positive lead (if email not already in pipeline).",
        "negative": "Filtered out — no lead created.",
        "skipped": "Matched filter but no positive/negative signal — no lead.",
        "ignored": "Did not match filter keywords — skipped.",
    }
    return InboundMailTestClassifyOut(
        filter_matched=bool(result["filter_matched"]),
        classification=classification,
        matched_filter_terms=list(result.get("matched_filter_terms") or []),
        matched_sentiment_terms=list(result.get("matched_sentiment_terms") or []),
        would_create_lead=would_create,
        note=notes.get(classification, ""),
    )


@router.post("/self-test", response_model=InboundMailSelfTestOut)
def self_test(db: Session = Depends(get_db)):
    """Send spam + positive self-emails via Gmail, then run inbox poll."""
    try:
        result = run_live_self_test(db)
    except GmailAuthError as exc:
        raise HTTPException(400, str(exc)) from exc
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(502, f"Live Gmail self-test failed: {exc}") from exc

    events = [
        InboundMailEventOut.model_validate(ev) for ev in (result.get("events") or [])
    ]
    poll_raw = result.get("poll") or {}
    return InboundMailSelfTestOut(
        sent=list(result.get("sent") or []),
        poll=InboundMailRunOut(**poll_raw) if poll_raw else None,
        events=events,
        message=result.get("message") or "",
    )


@router.get("/events", response_model=list[InboundMailEventOut])
def events(limit: int = Query(50, ge=1, le=200), db: Session = Depends(get_db)):
    return list_events(db, limit=limit)
