"""OpenAI tool-calling agent: plan (dry-run) and execute modes."""

from __future__ import annotations

import io
import json
import re
from functools import lru_cache
from typing import Any

from sqlalchemy.orm import Session

from app.agent.tools import (
    MUTATING_TOOLS,
    TOOL_DEFINITIONS,
    AmbiguousLeadError,
    dispatch_tool,
    resolve_leads,
)
from app.config import PIPELINE_STAGES, settings
from app.email_service import EmailSendError


# Common Whisper / accent mishearings in this CRM domain
_TRANSCRIPT_FIXES = (
    (r"\blids\b", "leads"),
    (r"\bleds\b", "leads"),
    (r"\bleed\b", "lead"),
    (r"\bfollow[\s-]?ups?\b", "follow-up"),
    (r"\bworm\b", "warm"),
    (r"\bwarm lid\b", "warm lead"),
    (r"\bwarm lids\b", "warm leads"),
)


def normalize_transcript(transcript: str) -> str:
    text = (transcript or "").strip()
    for pattern, repl in _TRANSCRIPT_FIXES:
        text = re.sub(pattern, repl, text, flags=re.IGNORECASE)
    return text


def _stage_from_transcript(text: str) -> str | None:
    lowered = text.casefold()
    # Prefer longer stage names first
    for stage in sorted(PIPELINE_STAGES, key=len, reverse=True):
        if stage.casefold() in lowered:
            return stage
    # Loose aliases
    aliases = {
        "warm": "Warm lead",
        "positive": "Positive lead",
        "new lead": "New Lead",
        "needs to send": "Needs to send",
        "call scheduled": "Call Scheduled",
        "overdue": None,  # not a stage — handled separately
    }
    for key, stage in aliases.items():
        if key in lowered and stage:
            return stage
    return None


def _is_lookup_intent(text: str) -> bool:
    t = text.casefold()
    return any(
        w in t
        for w in (
            "show",
            "list",
            "find",
            "who",
            "which",
            "lookup",
            "search",
            "warm lead",
            "warm leads",
        )
    )


def _fallback_lookup(db: Session, transcript: str) -> dict | None:
    """If the model skipped tools on a clear lookup, resolve locally."""
    if not _is_lookup_intent(transcript):
        return None
    stage = _stage_from_transcript(transcript)
    overdue_only = "overdue" in transcript.casefold()
    result = resolve_leads(
        db,
        query=None if stage or overdue_only else transcript,
        stage=stage,
        overdue_only=overdue_only,
    )
    names = ", ".join(
        f"{l['lead_code']} {l['contact_name']}" for l in result.get("leads", [])[:8]
    )
    summary = (
        f"Found {result.get('count', 0)} lead(s)"
        + (f" in stage “{stage}”" if stage else "")
        + (f": {names}" if names else ".")
    )
    return {
        "transcript": transcript,
        "summary": summary,
        "actions": [
            {
                "tool": "resolve_leads",
                "args": {"stage": stage, "overdue_only": overdue_only},
                "preview": result,
                "result": result,
                "error": None,
                "status": "planned",
            }
        ],
        "errors": [],
        "needs_disambiguation": False,
    }


def _clean_who(raw: str) -> str:
    return re.sub(r"[.?!]+$", "", (raw or "").strip()).strip(" \"'")


def _intent_kind(text: str) -> str | None:
    """Classify a spoken CRM command without an LLM."""
    t = text.casefold()
    if re.search(r"\b(all|every|each|everyone|everybody)\b", t):
        return "batch"
    if _is_lookup_intent(text) and not any(
        w in t for w in ("send", "email", "mark", "note", "move", "update", "change")
    ):
        return "lookup"
    if "note" in t and any(w in t for w in ("add", "append", "write")):
        return "note"
    if "mark" in t and "done" in t:
        return "mark"
    if any(w in t for w in ("send", "email")) or "follow" in t:
        return "send"
    if any(w in t for w in ("move", "change", "update", "set")) and _stage_from_transcript(text):
        return "move"
    return None


def _leads_mentioned(db: Session, text: str) -> list[Lead]:
    """Find leads whose code/name appears in the transcript (fuzzy, order-stable)."""
    from app.models import Lead

    lowered = text.casefold()
    rows = db.query(Lead).order_by(Lead.sort_order, Lead.id).all()
    hits: list[Lead] = []
    for lead in rows:
        code = (lead.lead_code or "").casefold()
        name = (lead.contact_name or "").casefold().strip()
        email = (lead.client_email or "").casefold()
        if code and code in lowered:
            hits.append(lead)
            continue
        if email and email in lowered:
            hits.append(lead)
            continue
        if name and name in lowered:
            hits.append(lead)
            continue
        parts = [p for p in re.split(r"\s+", name) if len(p) >= 3]
        if len(parts) >= 2 and all(p in lowered for p in parts):
            hits.append(lead)
            continue
    if hits:
        return hits

    # Single distinctive name token (e.g. "Alex" → Alex Rivera) if unique among leads
    token_hits: dict[str, list[Lead]] = {}
    for lead in rows:
        for part in re.split(r"\s+", (lead.contact_name or "").casefold()):
            if len(part) < 4:
                continue
            if re.search(rf"\b{re.escape(part)}\b", lowered):
                token_hits.setdefault(part, []).append(lead)
    unique = [leads[0] for leads in token_hits.values() if len(leads) == 1]
    # Dedupe while preserving order
    seen: set[int] = set()
    out: list[Lead] = []
    for lead in unique:
        if lead.id not in seen:
            seen.add(lead.id)
            out.append(lead)
    return out


def _note_text_from_transcript(text: str) -> str:
    m = re.search(
        r"(?:note|saying|that)\s*(?:to|on|for)?\s*.+?\s*(?:[:\-]|saying|that)\s*(.+)$",
        text,
        re.I,
    )
    if m:
        return _clean_who(m.group(1))
    # Fallback: strip the lead name / command words
    cleaned = re.sub(
        r"\b(add|append|a|note|to|on|for|saying|that)\b",
        " ",
        text,
        flags=re.I,
    )
    return _clean_who(re.sub(r"\s+", " ", cleaned))


def _action_for_lead(
    db: Session,
    *,
    kind: str,
    lead: Lead,
    text: str,
    transcript: str,
) -> dict | None:
    """Build one dry-run tool entry for a single matched lead."""
    tool: str | None = None
    args: dict[str, Any] = {"lead_id": lead.id, "lead": lead.contact_name}

    if kind == "send":
        tool = "send_follow_up_email"
        fu = re.search(r"\b(?:fu|follow[\s-]?up)\s*(?:number|num|#)?\s*(\d)\b", text, re.I)
        if fu:
            args["fu_number"] = int(fu.group(1))
    elif kind == "mark":
        tool = "mark_follow_up_done"
        fu = re.search(r"\b(?:fu|follow[\s-]?up)\s*(?:number|num|#)?\s*(\d)\b", text, re.I)
        if fu:
            args["fu_number"] = int(fu.group(1))
    elif kind == "move":
        stage = _stage_from_transcript(text)
        if not stage:
            return None
        tool = "update_lead_stage"
        args["stage"] = stage
    elif kind == "note":
        note = _note_text_from_transcript(text)
        for m in _leads_mentioned(db, text):
            note = re.sub(re.escape(m.contact_name), "", note, flags=re.I)
        note = note.strip(" -:.,")
        if not note:
            note = "Follow-up note"
        tool = "append_lead_note"
        args["text"] = note
    else:
        return None

    entry, _out = _run_one_tool(db, tool, args, dry_run=True, transcript=transcript)
    return entry


def _try_local_action_plan(db: Session, transcript: str) -> dict | None:
    """Plan common voice commands locally (no OpenAI) by matching lead names in text.

    Multiple distinct names ("send follow-up to Sam, Nitin and Mark") → one action each.
    """
    text = transcript.strip()
    if not text:
        return None

    kind = _intent_kind(text)
    if kind is None:
        return None
    if kind == "lookup":
        return _fallback_lookup(db, text)
    if kind == "batch":
        # "all overdue / all warm leads" — resolve by stage, then act
        return _try_stage_batch_plan(db, text)

    matches = _leads_mentioned(db, text)
    if not matches:
        return {
            "transcript": text,
            "summary": "I couldn't tell which lead you meant. Say a full name or lead code (e.g. L-101).",
            "actions": [],
            "errors": [],
            "needs_disambiguation": True,
        }

    # Cap multi-name commands (same limit as the LLM batch path)
    capped = matches[:MAX_BATCH_ACTIONS]
    skipped = len(matches) - len(capped)

    actions: list[dict] = []
    errors: list[str] = []
    for lead in capped:
        entry = _action_for_lead(
            db, kind=kind, lead=lead, text=text, transcript=transcript
        )
        if entry is None:
            return None
        if entry.get("error"):
            errors.append(f"{entry['tool']}: {entry['error']}")
        actions.append(entry)

    if skipped:
        errors.append(
            f"Only the first {MAX_BATCH_ACTIONS} leads were planned; "
            f"{skipped} more skipped. Run again for the rest."
        )

    return _finish(transcript, actions, errors)


def _try_stage_batch_plan(db: Session, text: str) -> dict | None:
    """Handle 'send follow-up to all warm leads' / 'all overdue' locally."""
    kind_send = any(w in text.casefold() for w in ("send", "email", "follow"))
    kind_mark = "mark" in text.casefold() and "done" in text.casefold()
    if not kind_send and not kind_mark:
        return None

    overdue_only = "overdue" in text.casefold()
    stage = None if overdue_only else _stage_from_transcript(text)
    if not overdue_only and not stage:
        return None

    found = resolve_leads(db, stage=stage, overdue_only=overdue_only)
    leads = found.get("leads") or []
    if not leads:
        return {
            "transcript": text,
            "summary": "No leads matched that filter.",
            "actions": [],
            "errors": [],
            "needs_disambiguation": False,
        }

    tool = "send_follow_up_email" if kind_send else "mark_follow_up_done"
    actions: list[dict] = []
    errors: list[str] = []
    for item in leads[:MAX_BATCH_ACTIONS]:
        entry, _out = _run_one_tool(
            db,
            tool,
            {"lead_id": item["lead_id"], "lead": item["contact_name"]},
            dry_run=True,
            transcript=text,
        )
        if entry.get("error"):
            errors.append(f"{tool}: {entry['error']}")
        actions.append(entry)
    if len(leads) > MAX_BATCH_ACTIONS:
        errors.append(
            f"Only the first {MAX_BATCH_ACTIONS} of {len(leads)} leads were planned."
        )
    return _finish(text, actions, errors)


SYSTEM_PROMPT = """Lead follow-up agent for a CRM. Act with tools only; never chat.
- Actions on a person: call the action tool directly with lead="<name/email/code as spoken>".
  Do NOT call resolve_leads first.
- "send follow-up/email" → send_follow_up_email.
- "mark ... done" → mark_follow_up_done only (never send an email for it).
- "move/set stage" → update_lead_stage. "add note" → append_lead_note.
- Call only the tools the user asked for. Several people → one call each.
- Never guess between leads with similar names.
- Lookups ("show/list/find warm leads", "who is overdue") → resolve_leads.
- Batch ("send to all overdue/warm leads") → resolve_leads, then one action per lead_id (max 5).
"""


def _is_reasoning_model(model: str) -> bool:
    m = model.casefold()
    return m.startswith(("gpt-5", "o1", "o3", "o4"))


@lru_cache(maxsize=4)
def _build_client(api_key: str, timeout: float):
    from openai import OpenAI

    # One shared client = one pooled HTTPS connection (no TLS handshake per call)
    return OpenAI(api_key=api_key, timeout=timeout, max_retries=1)


def _openai_client():
    if not settings.openai_api_key:
        raise RuntimeError(
            "OPENAI_API_KEY is not set. Add it to backend/.env to use the voice agent."
        )
    return _build_client(settings.openai_api_key, settings.openai_timeout_seconds)


_STT_PROMPT = (
    "Voice command for a sales leads CRM. Vocabulary: lead, leads, follow-up, FU, "
    "warm lead, overdue, mark done, send email, stage, note, lead code L-001."
)


def transcribe_audio(audio_bytes: bytes, filename: str = "audio.webm") -> str:
    client = _openai_client()
    bio = io.BytesIO(audio_bytes)
    bio.name = filename  # API uses the extension to detect the audio format
    kwargs: dict[str, Any] = {
        "model": settings.openai_stt_model,
        "file": bio,
        "prompt": _STT_PROMPT,
    }
    if settings.openai_stt_language:
        kwargs["language"] = settings.openai_stt_language
    result = client.audio.transcriptions.create(**kwargs)
    return (result.text or "").strip()


def _completion_kwargs(messages: list[dict], *, first_round: bool) -> dict[str, Any]:
    model = settings.openai_model
    kwargs: dict[str, Any] = {
        "model": model,
        "messages": messages,
        "tools": TOOL_DEFINITIONS,
        # Every valid command maps to a tool. Forcing one on the first round stops
        # fast/minimal-reasoning models from replying "I will send…" in plain text.
        "tool_choice": "required" if first_round else "auto",
    }
    if _is_reasoning_model(model):
        effort = settings.openai_reasoning_effort or "minimal"
        # o-series has no "minimal" level
        if effort == "minimal" and not model.casefold().startswith("gpt-5"):
            effort = "low"
        kwargs["reasoning_effort"] = effort
        kwargs["max_completion_tokens"] = 2048
    else:
        kwargs["temperature"] = 0.1
        kwargs["max_completion_tokens"] = 600
    return kwargs


def _describe_action(entry: dict) -> str:
    out = entry.get("preview") or {}
    who = f"{out.get('contact_name', '?')} ({out.get('lead_code', '?')})"
    tool = entry["tool"]
    if entry.get("status") == "failed":
        return f"{tool} failed: {entry.get('error')}"
    if tool == "send_follow_up_email":
        return f"Send FU {out.get('follow_up_number')} email to {who}"
    if tool == "mark_follow_up_done":
        return f"Mark FU {out.get('follow_up_number')} done for {who}"
    if tool == "update_lead_stage":
        return f"Move {who} to “{out.get('to_stage')}”"
    if tool == "append_lead_note":
        return f"Add note to {who}"
    if tool == "resolve_leads":
        return f"Found {out.get('count', 0)} lead(s)"
    return tool


def _local_summary(actions: list[dict]) -> str:
    parts = [_describe_action(a) for a in actions if a["tool"] in MUTATING_TOOLS]
    return "; ".join(parts) + "." if parts else ""


def _run_one_tool(
    db: Session, name: str, args: dict, *, dry_run: bool, transcript: str
) -> tuple[dict, dict]:
    """Run a single tool call. Returns (ui_entry, payload_for_model)."""
    entry: dict[str, Any] = {
        "tool": name,
        "args": args,
        "preview": None,
        "result": None,
        "error": None,
        "status": "planned" if dry_run else "executed",
    }
    try:
        # resolve_leads is read-only, so it always runs for real
        mutate_dry = dry_run and name in MUTATING_TOOLS
        out = dispatch_tool(db, name, args, dry_run=mutate_dry, transcript=transcript)
        entry["preview"] = out
        if not dry_run:
            entry["result"] = out
        if mutate_dry and out.get("follow_up_number") is not None:
            # Pin FU number so Approve executes exactly what was previewed
            args.setdefault("fu_number", out["follow_up_number"])
    except AmbiguousLeadError as exc:
        entry.update(error=str(exc), status="failed", preview={"count": len(exc.matches), "leads": exc.matches})
        entry["ambiguous"] = True
        out = {"error": str(exc)}
    except (EmailSendError, ValueError, RuntimeError, KeyError, TypeError) as exc:
        entry.update(error=str(exc), status="failed")
        out = {"error": str(exc)}
    return entry, out


def _run_tool_loop(
    db: Session,
    transcript: str,
    *,
    dry_run: bool,
) -> dict[str, Any]:
    client = _openai_client()
    messages: list[dict] = [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": transcript},
    ]
    actions: list[dict] = []
    errors: list[str] = []
    max_rounds = 4

    for round_no in range(max_rounds):
        response = client.chat.completions.create(
            **_completion_kwargs(messages, first_round=round_no == 0)
        )
        choice = response.choices[0]
        msg = choice.message

        if not msg.tool_calls:
            if choice.finish_reason == "length":
                raise RuntimeError("Model hit max tokens before choosing an action.")
            return _finish(transcript, actions, errors, model_text=msg.content)

        messages.append(
            {
                "role": "assistant",
                "content": msg.content,
                "tool_calls": [
                    {
                        "id": tc.id,
                        "type": "function",
                        "function": {
                            "name": tc.function.name,
                            "arguments": tc.function.arguments,
                        },
                    }
                    for tc in msg.tool_calls
                ],
            }
        )

        round_tools: set[str] = set()
        for tc in msg.tool_calls:
            try:
                args = json.loads(tc.function.arguments or "{}")
            except json.JSONDecodeError:
                args = {}
            entry, out = _run_one_tool(
                db, tc.function.name, args, dry_run=dry_run, transcript=transcript
            )
            if entry["error"]:
                errors.append(f"{entry['tool']}: {entry['error']}")
            actions.append(entry)
            round_tools.add(entry["tool"])
            messages.append(
                {"role": "tool", "tool_call_id": tc.id, "content": json.dumps(out, default=str)}
            )

        # Safety: a single person was named but several leads match → never let the
        # model guess (it may pick one, or email all of them). Ask the user instead.
        if not _is_batch_intent(transcript) and any(
            a["tool"] == "resolve_leads"
            and (a.get("args") or {}).get("query")
            and (a.get("preview") or {}).get("count", 0) > 1
            for a in actions
        ):
            return _finish(transcript, actions, errors, force_disambiguation=True)

        # Early exit: once the model has chosen its actions there is nothing left
        # to decide — skip the extra "write a summary" round-trip (saves ~5-10s).
        if round_tools <= MUTATING_TOOLS:
            return _finish(transcript, actions, errors)

    return _finish(transcript, actions, errors + ["Agent exceeded max tool rounds"])


MAX_BATCH_ACTIONS = 5

_BATCH_WORDS = re.compile(r"\b(all|every|each|everyone|everybody|overdue)\b", re.IGNORECASE)


def _is_batch_intent(text: str) -> bool:
    """"Send to all overdue leads" — the user really means several leads."""
    return bool(_BATCH_WORDS.search(text)) or _stage_from_transcript(text) is not None


def _finish(
    transcript: str,
    actions: list[dict],
    errors: list[str],
    *,
    model_text: str | None = None,
    force_disambiguation: bool = False,
) -> dict[str, Any]:
    if force_disambiguation or any(a.get("ambiguous") for a in actions):
        matches = next(
            (a["preview"]["leads"] for a in actions if (a.get("preview") or {}).get("count", 0) > 1),
            [],
        )
        # Drop half-planned mutations (keep the ambiguous entry so the UI lists matches)
        actions = [a for a in actions if a["tool"] not in MUTATING_TOOLS or a.get("ambiguous")]
        names = ", ".join(f"{m['lead_code']} {m['contact_name']}" for m in matches[:8])
        return {
            "transcript": transcript,
            "summary": f"Several leads match — say which one: {names}.",
            "actions": actions,
            "errors": errors,
            "needs_disambiguation": True,
        }
    mutating = [a for a in actions if a["tool"] in MUTATING_TOOLS]
    if len(mutating) > MAX_BATCH_ACTIONS:
        dropped = mutating[MAX_BATCH_ACTIONS:]
        actions = [a for a in actions if not any(a is d for d in dropped)]
        mutating = mutating[:MAX_BATCH_ACTIONS]
        errors = errors + [
            f"Only the first {MAX_BATCH_ACTIONS} actions were planned; "
            f"{len(dropped)} skipped. Run the command again for the rest."
        ]
    ambiguous = any(a.get("ambiguous") for a in actions)
    # Several matches and the model did not pick one → ask the user who they meant
    vague_lookup = not mutating and any(
        a["tool"] == "resolve_leads" and (a.get("preview") or {}).get("count", 0) > 1
        for a in actions
    ) and not _is_lookup_intent(transcript)
    summary = _local_summary(actions) or (model_text or "").strip()
    if not summary and actions:
        summary = _describe_action(actions[-1])
    return {
        "transcript": transcript,
        "summary": summary,
        "actions": actions,
        "errors": errors,
        "needs_disambiguation": ambiguous or vague_lookup,
    }


def plan_from_transcript(db: Session, transcript: str) -> dict:
    import time

    text = normalize_transcript(transcript)
    t0 = time.perf_counter()
    if not text:
        return {
            "transcript": "",
            "summary": "Empty transcript.",
            "actions": [],
            "errors": ["Transcript is empty"],
            "needs_disambiguation": False,
            "timings_ms": {"plan": 0},
        }

    # Always try the local (no-LLM) planner first — this is what keeps voice fast.
    local = _try_local_action_plan(db, text)
    if local:
        local["transcript"] = text
        local["timings_ms"] = {
            **(local.get("timings_ms") or {}),
            "plan": round((time.perf_counter() - t0) * 1000),
            "planner": 0,  # 0 = local
        }
        return local

    # Only multi-lead / odd phrasings fall through to the model (slow).
    try:
        result = _run_tool_loop(db, text, dry_run=True)
    except Exception:
        fallback = _fallback_lookup(db, text)
        if fallback:
            fallback["timings_ms"] = {"plan": round((time.perf_counter() - t0) * 1000)}
            return fallback
        raise
    result["transcript"] = text
    if not result.get("actions"):
        fallback = _fallback_lookup(db, text)
        if fallback:
            fallback["timings_ms"] = {"plan": round((time.perf_counter() - t0) * 1000)}
            return fallback
    result["timings_ms"] = {
        "plan": round((time.perf_counter() - t0) * 1000),
        "planner": 1,  # 1 = openai
    }
    return result


def execute_from_transcript(db: Session, transcript: str) -> dict:
    text = normalize_transcript(transcript)
    if not text:
        return {
            "transcript": "",
            "summary": "Empty transcript.",
            "actions": [],
            "errors": ["Transcript is empty"],
            "success": False,
        }
    result = _run_tool_loop(db, text, dry_run=False)
    result["transcript"] = text
    mutating = [a for a in result.get("actions", []) if a.get("tool") in MUTATING_TOOLS]
    if mutating:
        result["success"] = all(a.get("status") == "executed" for a in mutating) and not result.get(
            "errors"
        )
    else:
        result["success"] = not result.get("errors")
    return result


def execute_actions(
    db: Session,
    actions: list[dict],
    *,
    transcript: str | None = None,
) -> dict:
    """Execute a confirmed list of mutating actions (from plan UI)."""
    results: list[dict] = []
    errors: list[str] = []
    for raw in actions:
        name = raw.get("tool") or raw.get("name")
        args = raw.get("args") or {}
        if name not in MUTATING_TOOLS:
            # Skip resolve_leads on execute path
            if name == "resolve_leads":
                continue
            errors.append(f"Cannot execute tool: {name}")
            continue
        entry: dict[str, Any] = {
            "tool": name,
            "args": args,
            "preview": raw.get("preview"),
            "result": None,
            "error": None,
            "status": "executed",
        }
        try:
            out = dispatch_tool(
                db, name, args, dry_run=False, transcript=transcript
            )
            entry["result"] = out
            entry["preview"] = out
        except (EmailSendError, ValueError, RuntimeError) as exc:
            entry["error"] = str(exc)
            entry["status"] = "failed"
            errors.append(f"{name}: {exc}")
        results.append(entry)

    success = bool(results) and all(a["status"] == "executed" for a in results)
    return {
        "transcript": transcript or "",
        "summary": "Executed confirmed actions." if success else "Some actions failed.",
        "actions": results,
        "errors": errors,
        "success": success,
    }
