"""Agent tool implementations (plan dry-run vs execute)."""

from __future__ import annotations

from sqlalchemy import or_
from sqlalchemy.orm import Session, joinedload

from app.config import PIPELINE_STAGES
from app.email_service import (
    EmailSendError,
    next_pending_follow_up,
    preview_follow_up_email,
    send_follow_up_email,
)
from app.models import Lead
from app.schemas import LeadUpdate
from app import crud
from app.services import mark_follow_up


# Every action tool accepts either ``lead`` (name / email / code, resolved
# server-side) or ``lead_id``. Passing ``lead`` lets the model act in a single
# round-trip instead of calling resolve_leads first — the main latency win.
_LEAD_REF = {
    "lead": {
        "type": "string",
        "description": "Person name, email or lead code (e.g. 'Sarah', 'L-012').",
    },
    "lead_id": {"type": "integer", "description": "Only if known from resolve_leads."},
}

TOOL_DEFINITIONS = [
    {
        "type": "function",
        "function": {
            "name": "resolve_leads",
            "description": "List/find leads by name, email, code, website, stage or overdue. "
            "Use for lookups and stage/overdue batches.",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string"},
                    "stage": {"type": "string", "enum": PIPELINE_STAGES},
                    "overdue_only": {"type": "boolean"},
                },
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "send_follow_up_email",
            "description": "Send the next pending (or given) follow-up email to a lead.",
            "parameters": {
                "type": "object",
                "properties": {**_LEAD_REF, "fu_number": {"type": "integer"}},
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "mark_follow_up_done",
            "description": "Mark a follow-up done WITHOUT sending email "
            "(next pending FU if fu_number omitted).",
            "parameters": {
                "type": "object",
                "properties": {**_LEAD_REF, "fu_number": {"type": "integer"}},
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "update_lead_stage",
            "description": "Set a lead's pipeline stage.",
            "parameters": {
                "type": "object",
                "properties": {
                    **_LEAD_REF,
                    "stage": {"type": "string", "enum": PIPELINE_STAGES},
                },
                "required": ["stage"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "append_lead_note",
            "description": "Append text to a lead's notes.",
            "parameters": {
                "type": "object",
                "properties": {**_LEAD_REF, "text": {"type": "string"}},
                "required": ["text"],
            },
        },
    },
]


class AmbiguousLeadError(ValueError):
    """``lead`` text matched more than one lead — the user must be more specific."""

    def __init__(self, query: str, matches: list[dict]):
        self.query = query
        self.matches = matches
        names = ", ".join(f"{m['lead_code']} {m['contact_name']}" for m in matches[:8])
        super().__init__(f"'{query}' matches {len(matches)} leads: {names}. Be more specific.")


def _resolve_lead_id(db: Session, args: dict) -> int:
    """Turn ``lead_id`` or free-text ``lead`` into exactly one lead id."""
    if args.get("lead_id") is not None:
        return int(args["lead_id"])
    ref = str(args.get("lead") or args.get("query") or "").strip()
    if not ref:
        raise ValueError("Which lead? Say a name, email or lead code.")
    found = resolve_leads(db, query=ref)["leads"]
    if not found:
        raise ValueError(f"No lead matches '{ref}'")
    if len(found) > 1:
        # Prefer an exact (case-insensitive) name / email / code match
        exact = [
            m
            for m in found
            if ref.casefold()
            in (m["contact_name"].casefold(), m["client_email"].casefold(), m["lead_code"].casefold())
        ]
        if len(exact) != 1:
            raise AmbiguousLeadError(ref, found)
        found = exact
    return found[0]["lead_id"]


def _lead_summary(lead: Lead) -> dict:
    pending = next_pending_follow_up(lead)
    return {
        "lead_id": lead.id,
        "lead_code": lead.lead_code,
        "contact_name": lead.contact_name,
        "client_email": lead.client_email,
        "stage": lead.stage,
        "next_pending_fu": pending.number if pending else None,
        "next_pending_day": pending.day_label if pending else None,
    }


def resolve_leads(
    db: Session,
    *,
    query: str | None = None,
    stage: str | None = None,
    overdue_only: bool = False,
) -> dict:
    from datetime import date

    from app.services import compute_fu_state

    q = db.query(Lead).options(joinedload(Lead.follow_ups))
    if query and query.strip():
        like = f"%{query.strip()}%"
        q = q.filter(
            or_(
                Lead.contact_name.ilike(like),
                Lead.client_email.ilike(like),
                Lead.lead_code.ilike(like),
                Lead.website.ilike(like),
                Lead.notes.ilike(like),
            )
        )
    if stage and stage.strip():
        q = q.filter(Lead.stage == stage.strip())

    leads = q.order_by(Lead.sort_order, Lead.id).limit(25).all()
    today = date.today()
    results = []
    for lead in leads:
        if overdue_only:
            pending = next_pending_follow_up(lead)
            if not pending or compute_fu_state(pending, today) != "overdue":
                continue
        results.append(_lead_summary(lead))
    return {"count": len(results), "leads": results}


def _get_lead(db: Session, lead_id: int) -> Lead:
    lead = (
        db.query(Lead)
        .options(joinedload(Lead.follow_ups))
        .filter(Lead.id == lead_id)
        .first()
    )
    if not lead:
        raise ValueError(f"Lead id {lead_id} not found")
    return lead


def tool_send_follow_up_email(
    db: Session,
    *,
    lead_id: int,
    fu_number: int | None = None,
    dry_run: bool = True,
    transcript: str | None = None,
) -> dict:
    lead = _get_lead(db, lead_id)
    number = fu_number
    if number is None:
        pending = next_pending_follow_up(lead)
        if not pending:
            raise ValueError(f"No pending follow-ups for {lead.lead_code}")
        number = pending.number
    if dry_run:
        preview = preview_follow_up_email(lead, number)
        return {
            **preview,
            "dry_run": True,
            "status": "planned",
            "will_mark_done": True,
            "follow_up_number": number,
        }
    # Successful send always marks that FU as Done
    return send_follow_up_email(
        db,
        lead,
        number,
        dry_run=False,
        transcript_snippet=transcript,
        mark_done=True,
    )


def tool_mark_follow_up_done(
    db: Session, *, lead_id: int, fu_number: int | None = None, dry_run: bool = True
) -> dict:
    lead = _get_lead(db, lead_id)
    if fu_number is None:
        fu = next_pending_follow_up(lead)
        if not fu:
            raise ValueError(f"No pending follow-ups for {lead.lead_code}")
        fu_number = fu.number
    else:
        fu = next((f for f in lead.follow_ups if f.number == fu_number), None)
    if not fu:
        raise ValueError(f"FU {fu_number} not found for {lead.lead_code}")
    preview = {
        "lead_id": lead.id,
        "lead_code": lead.lead_code,
        "contact_name": lead.contact_name,
        "follow_up_number": fu_number,
        "day_label": fu.day_label,
        "action": "mark_done",
        "will_mark_done": True,
    }
    if dry_run:
        return {**preview, "dry_run": True, "status": "planned"}
    mark_follow_up(fu, "done")
    db.commit()
    return {**preview, "dry_run": False, "status": "done", "follow_up_status": "done"}


def tool_update_lead_stage(
    db: Session, *, lead_id: int, stage: str, dry_run: bool = True
) -> dict:
    if stage not in PIPELINE_STAGES:
        raise ValueError(f"Invalid stage: {stage}")
    lead = _get_lead(db, lead_id)
    preview = {
        "lead_id": lead.id,
        "lead_code": lead.lead_code,
        "contact_name": lead.contact_name,
        "from_stage": lead.stage,
        "to_stage": stage,
    }
    if dry_run:
        return {**preview, "dry_run": True, "status": "planned"}
    updated = crud.update_lead(db, lead, LeadUpdate(stage=stage))
    return {
        **preview,
        "dry_run": False,
        "status": "updated",
        "stage": updated.stage,
    }


def tool_append_lead_note(
    db: Session, *, lead_id: int, text: str, dry_run: bool = True
) -> dict:
    lead = _get_lead(db, lead_id)
    note = (text or "").strip()
    if not note:
        raise ValueError("Note text is empty")
    preview = {
        "lead_id": lead.id,
        "lead_code": lead.lead_code,
        "contact_name": lead.contact_name,
        "note": note,
    }
    if dry_run:
        return {**preview, "dry_run": True, "status": "planned"}
    existing = (lead.notes or "").rstrip()
    new_notes = f"{existing}\n{note}".strip() if existing else note
    updated = crud.update_lead(db, lead, LeadUpdate(notes=new_notes))
    return {**preview, "dry_run": False, "status": "updated", "notes": updated.notes}


def _opt_int(value) -> int | None:
    return int(value) if value is not None else None


def dispatch_tool(
    db: Session,
    name: str,
    args: dict,
    *,
    dry_run: bool = True,
    transcript: str | None = None,
) -> dict:
    if name == "resolve_leads":
        return resolve_leads(
            db,
            query=args.get("query"),
            stage=args.get("stage"),
            overdue_only=bool(args.get("overdue_only")),
        )
    if name not in MUTATING_TOOLS:
        raise ValueError(f"Unknown tool: {name}")

    lead_id = _resolve_lead_id(db, args)
    # Pin the resolved id so an approved plan executes against the same lead
    args["lead_id"] = lead_id
    if name == "send_follow_up_email":
        return tool_send_follow_up_email(
            db,
            lead_id=lead_id,
            fu_number=_opt_int(args.get("fu_number")),
            dry_run=dry_run,
            transcript=transcript,
        )
    if name == "mark_follow_up_done":
        return tool_mark_follow_up_done(
            db, lead_id=lead_id, fu_number=_opt_int(args.get("fu_number")), dry_run=dry_run
        )
    if name == "update_lead_stage":
        return tool_update_lead_stage(
            db, lead_id=lead_id, stage=args.get("stage") or "", dry_run=dry_run
        )
    return tool_append_lead_note(
        db, lead_id=lead_id, text=args.get("text") or "", dry_run=dry_run
    )


# Side-effect tools that need user confirm before execute
MUTATING_TOOLS = {
    "send_follow_up_email",
    "mark_follow_up_done",
    "update_lead_stage",
    "append_lead_note",
}
