"""
Coview server-side Claude consumer.

When a browser-sent note lands on the coview WebSocket, the server spawns
`respond_to_note(...)` as a background task. This module routes each inference
turn through keeper dispatch, broadcasts tokens back over WS as `note_stream`
actions, handles tool use (highlight / load_folio / search_vms / get_folio_info), and
appends the final reply to `_coview_state["notes"]`.

Persona + model + tuning live in `coview_persona.md` (re-read each turn, so
edits take effect without a restart).
"""
from __future__ import annotations

import asyncio
import json
import os
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any, Awaitable, Callable, Optional

import httpx

from . import coview_db
from .keeper_dispatch import run_logged_dispatch


# ── Config ──────────────────────────────────────────────────────────────

PERSONA_FILE = Path(__file__).parent / "coview_persona.md"
KEY_FILE = Path.home() / ".config" / "cat" / "anthropic_key.txt"
INTERNAL_API_BASE = os.environ.get("COVIEW_INTERNAL_API", "retained local service")
MAX_TOOL_LOOPS = 6


def _get_api_key() -> Optional[str]:
    key = os.environ.get("ANTHROPIC_API_KEY")
    if key:
        return key.strip()
    if KEY_FILE.exists():
        return KEY_FILE.read_text().strip()
    return None


def _load_persona() -> dict:
    """Re-read persona file every turn so edits take effect without a restart."""
    defaults = {
        "provider": "anthropic",
        "model": "claude-opus-4-7",
        "ollama_model": "qwen3:14b",
        "ollama_url": "retained local service",
        "max_tokens": 2000,
        "effort": "high",
        "history_turns": 20,
        "system": "You are Claude, assisting with Voynich manuscript research.",
    }
    if not PERSONA_FILE.exists():
        return defaults
    text = PERSONA_FILE.read_text()
    if text.startswith("---"):
        parts = text.split("---", 2)
        if len(parts) >= 3:
            meta_raw, body = parts[1], parts[2]
            for line in meta_raw.splitlines():
                line = line.strip()
                if not line or ":" not in line:
                    continue
                k, v = line.split(":", 1)
                k, v = k.strip(), v.strip()
                if k in ("max_tokens", "history_turns"):
                    try:
                        defaults[k] = int(v)
                    except ValueError:
                        pass
                elif k in ("provider", "model", "ollama_model", "ollama_url", "effort"):
                    defaults[k] = v
            defaults["system"] = body.strip()
            return defaults
    defaults["system"] = text.strip()
    return defaults


# ── Tool schemas ────────────────────────────────────────────────────────

TOOLS = [
    {
        "name": "highlight_region",
        "description": (
            "Draw a labeled rectangle on the currently loaded folio in the "
            "researcher's co-viewer. Coordinates are in folio image pixels "
            "(origin top-left). Use this when pointing at something visual — "
            "a line, a gloss, a detail in an illustration."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "x": {"type": "integer", "description": "top-left x in pixels"},
                "y": {"type": "integer", "description": "top-left y in pixels"},
                "w": {"type": "integer", "description": "width in pixels"},
                "h": {"type": "integer", "description": "height in pixels"},
                "label": {"type": "string", "description": "short label visible on the box"},
                "color": {
                    "type": "string",
                    "description": "hex color like #ff6600; optional",
                },
            },
            "required": ["x", "y", "w", "h", "label"],
        },
    },
    {
        "name": "load_folio",
        "description": (
            "Switch the shared folio everyone is viewing. Only use when the "
            "researcher asks to move, or when cross-folio comparison is the "
            "point. Existing highlights are cleared on folio change."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "folio_id": {
                    "type": "string",
                    "description": "Folio identifier like 'f1r', 'f67v', 'f85v3'",
                }
            },
            "required": ["folio_id"],
        },
    },
    {
        "name": "search_vms",
        "description": (
            "Full-text search the Voynich database (transcriptions, annotations, "
            "notes). Returns JSON matches with folio and line context."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {"type": "string", "description": "search string"},
                "limit": {
                    "type": "integer",
                    "description": "max results (default 10, cap 25)",
                },
            },
            "required": ["query"],
        },
    },
    {
        "name": "get_folio_info",
        "description": (
            "Look up metadata for a folio: section (herbal_a/b, stars, zodiac, "
            "balneo, rosette, pharma), quire, illustration type, notes."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "folio_id": {"type": "string"},
            },
            "required": ["folio_id"],
        },
    },
]


# ── Tool execution ──────────────────────────────────────────────────────

async def _tool_highlight(
    session_id: str,
    state: dict,
    inp: dict,
    broadcast: Callable[[dict], Awaitable[None]],
) -> str:
    hl = {
        "action": "highlight",
        "type": "rect",
        "x": int(inp["x"]),
        "y": int(inp["y"]),
        "w": int(inp["w"]),
        "h": int(inp["h"]),
        "label": inp.get("label", ""),
        "color": inp.get("color", "#ff6600"),
        "owner": "claude",
        "time": datetime.now().strftime("%H:%M:%S"),
    }
    state["highlights"].append(hl)
    coview_db.save_highlight(session_id, state.get("folio", "f1r"), hl)
    await broadcast(hl)
    return (
        f"Highlight drawn: ({hl['x']},{hl['y']}) size {hl['w']}×{hl['h']} "
        f"labeled '{hl['label']}' on folio {state.get('folio', '?')}."
    )


async def _tool_load_folio(
    session_id: str,
    state: dict,
    inp: dict,
    broadcast: Callable[[dict], Awaitable[None]],
) -> str:
    folio_id = str(inp["folio_id"]).strip().lower()
    if not folio_id.startswith("f"):
        folio_id = "f" + folio_id
    if folio_id != state.get("folio"):
        coview_db.set_folio(session_id, folio_id)
        fresh = coview_db.load_session(session_id)
        state["folio"] = fresh["folio"]
        state["highlights"] = fresh["highlights"]
        state["strokes"] = fresh["strokes"]
        state["arrows"] = fresh["arrows"]
        # Push a fresh state frame so every viewer re-hydrates
        await broadcast({"action": "state", **state})
    return f"Loaded folio {folio_id}."


async def _tool_search_vms(inp: dict) -> str:
    query = str(inp["query"])
    limit = min(int(inp.get("limit", 10)), 25)
    async with httpx.AsyncClient(base_url=INTERNAL_API_BASE, timeout=15) as http:
        r = await http.get("/api/db/search", params={"q": query, "limit": limit})
        r.raise_for_status()
        body = r.text
    return body[:4000] if len(body) > 4000 else body


async def _tool_get_folio_info(inp: dict) -> str:
    folio_id = str(inp["folio_id"]).strip().lower()
    if not folio_id.startswith("f"):
        folio_id = "f" + folio_id
    async with httpx.AsyncClient(base_url=INTERNAL_API_BASE, timeout=15) as http:
        r = await http.get("/api/db/folios")
        r.raise_for_status()
        data = r.json()
    match = next((f for f in data if f.get("folio_id") == folio_id), None)
    if not match:
        return f"No DB record for folio {folio_id}."
    return json.dumps(match)


async def _execute_tool(
    name: str,
    inp: dict,
    session_id: str,
    state: dict,
    broadcast: Callable[[dict], Awaitable[None]],
) -> tuple[str, bool]:
    """Returns (result_text, is_error)."""
    try:
        if name == "highlight_region":
            return await _tool_highlight(session_id, state, inp, broadcast), False
        if name == "load_folio":
            return await _tool_load_folio(session_id, state, inp, broadcast), False
        if name == "search_vms":
            return await _tool_search_vms(inp), False
        if name == "get_folio_info":
            return await _tool_get_folio_info(inp), False
        return f"Unknown tool: {name}", True
    except Exception as e:
        return f"{type(e).__name__}: {e}", True


# ── Context builders ────────────────────────────────────────────────────

def _build_folio_context(state: dict) -> str:
    folio = state.get("folio", "?")
    highlights = state.get("highlights", [])
    lines = [f"Current folio: {folio}"]
    if highlights:
        lines.append(f"Existing highlights on this folio ({len(highlights)}):")
        for h in highlights[-10:]:
            owner = h.get("owner", "?")
            label = h.get("label") or "(unlabeled)"
            lines.append(
                f"  - [{owner}] '{label}' at ({h.get('x')},{h.get('y')}) "
                f"size {h.get('w')}×{h.get('h')}"
            )
    else:
        lines.append("No highlights placed yet on this folio.")
    return "\n".join(lines)


def _build_messages(state: dict, history_turns: int) -> list[dict]:
    """Convert the notes log into alternating user/assistant messages.

    Plain text — no owner prefix. Tagging user messages with `[ed]` was
    pattern-priming Qwen to echo the input back; if multi-participant ever
    matters we'll re-introduce it via a convention the model can't mistake
    for a formatting template."""
    messages: list[dict] = []
    recent = state.get("notes", [])[-history_turns:]
    for n in recent:
        owner = n.get("owner", "ed")
        text = (n.get("text") or "").strip()
        if not text:
            continue
        role = "assistant" if owner == "claude" else "user"
        if messages and messages[-1]["role"] == role:
            messages[-1]["content"] += f"\n\n{text}"
        else:
            messages.append({"role": role, "content": text})
    while messages and messages[0]["role"] != "user":
        messages.pop(0)
    return messages


# ── Main entry point ────────────────────────────────────────────────────

# Per-session locks so concurrent sessions don't serialize against each other.
_session_locks: dict[str, asyncio.Lock] = {}


def _get_lock(session_id: str) -> asyncio.Lock:
    lk = _session_locks.get(session_id)
    if lk is None:
        lk = asyncio.Lock()
        _session_locks[session_id] = lk
    return lk


async def _emit_stream_text(
    broadcast: Callable[[dict], Awaitable[None]],
    stream_id: str,
    text: str,
) -> None:
    if text:
        await broadcast(
            {
                "action": "note_stream",
                "stream_id": stream_id,
                "chunk": text,
                "owner": "claude",
            }
        )


async def respond_to_note(
    state: dict,
    incoming: dict,
    broadcast: Callable[[dict], Awaitable[None]],
    session_id: str = "terminal",
) -> None:
    """Handle one browser-sent note. Spawned as an asyncio task from the WS loop."""
    lock = _get_lock(session_id)
    if lock.locked():
        # In-flight response will pick up this note from state.notes on its next turn.
        return

    async with lock:
        try:
            await _respond(session_id, state, broadcast)
        except Exception as e:
            await broadcast({
                "action": "note",
                "text": f"[system] consumer error: {type(e).__name__}: {str(e)[:200]}",
                "owner": "system",
            })


async def _respond(
    session_id: str,
    state: dict,
    broadcast: Callable[[dict], Awaitable[None]],
) -> None:
    cfg = _load_persona()
    provider = cfg.get("provider", "anthropic")
    if provider == "ollama":
        await _respond_ollama(session_id, state, broadcast, cfg)
    else:
        await _respond_anthropic(session_id, state, broadcast, cfg)


def _ollama_tools() -> list[dict]:
    """Translate our TOOLS schema (Anthropic shape) to Ollama/OpenAI function shape."""
    return [
        {
            "type": "function",
            "function": {
                "name": t["name"],
                "description": t["description"],
                "parameters": t["input_schema"],
            },
        }
        for t in TOOLS
    ]


async def _respond_ollama(
    session_id: str,
    state: dict,
    broadcast: Callable[[dict], Awaitable[None]],
    cfg: dict,
) -> None:
    """Internal-testing path — streams chat from a local Ollama model.
    Supports the same 4 tools as the Anthropic path via Ollama's function-
    calling protocol (Qwen3 / Qwen2.5 tool-trained)."""
    messages = _build_messages(state, cfg["history_turns"])
    if not messages or messages[-1]["role"] != "user":
        return

    ollama_url = cfg.get("ollama_url", "retained local service").rstrip("/")
    model_name = cfg.get("ollama_model", "qwen3:14b")

    system_prompt = (
        cfg["system"]
        + "\n\n## Current co-viewer state\n\n"
        + _build_folio_context(state)
    )

    msgs: list[dict] = [
        {"role": "system", "content": system_prompt},
        *messages,
    ]
    tools_spec = _ollama_tools()
    stream_id = uuid.uuid4().hex[:8]
    accum_text: list[str] = []
    loops = 0

    while loops < MAX_TOOL_LOOPS:
        loops += 1
        result = await asyncio.to_thread(
            run_logged_dispatch,
            source="coview",
            connector="ollama",
            model=model_name,
            prompt="",
            mode="A",
            system_prompt=system_prompt,
            messages=msgs,
            tools=tools_spec,
            max_tokens=cfg["max_tokens"],
            temperature=0.3,
            ollama_url=ollama_url,
        )

        turn_str = (result.get("body") or "").strip()
        if turn_str:
            accum_text.append(turn_str)
            await _emit_stream_text(broadcast, stream_id, turn_str)

        tool_calls = result.get("tool_calls") or []

        if not tool_calls:
            # Done — finalize
            final = "\n\n".join(accum_text)
            await broadcast({
                "action": "note_stream_done",
                "stream_id": stream_id,
                "text": final,
                "owner": "claude",
            })
            if final:
                note = {
                    "action": "note",
                    "text": final,
                    "owner": "claude",
                    "time": datetime.now().strftime("%H:%M:%S"),
                }
                state["notes"].append(note)
                coview_db.save_note(session_id, note)
            return

        # Record assistant turn (with tool_calls) in history
        assistant_message = result.get("assistant_message") or {
            "role": "assistant",
            "content": turn_str,
            "tool_calls": [],
        }
        msgs.append(assistant_message)

        # Execute each tool, append tool-role responses
        for tc in tool_calls:
            name = tc.get("name", "")
            args = tc.get("input") or {}
            await broadcast({
                "action": "status",
                "text": f"using {name}({json.dumps(args)[:120]})",
                "owner": "claude",
            })
            result, is_error = await _execute_tool(
                name, args, session_id, state, broadcast
            )
            msgs.append({
                "role": "tool",
                "content": result if not is_error else f"ERROR: {result}",
            })

        # Fresh bubble for the next text turn
        stream_id = uuid.uuid4().hex[:8]

    # Hit loop cap
    await broadcast({
        "action": "note",
        "text": "[system] tool-loop cap reached.",
        "owner": "system",
    })


async def _respond_anthropic(
    session_id: str,
    state: dict,
    broadcast: Callable[[dict], Awaitable[None]],
    cfg: dict,
) -> None:
    messages = _build_messages(state, cfg["history_turns"])
    if not messages or messages[-1]["role"] != "user":
        return  # Nothing to respond to

    system = cfg["system"] + f"\n\n## Current co-viewer state\n\n{_build_folio_context(state)}"

    stream_id = uuid.uuid4().hex[:8]
    full_text_accum: list[str] = []
    loops = 0

    while loops < MAX_TOOL_LOOPS:
        loops += 1
        result = await asyncio.to_thread(
            run_logged_dispatch,
            source="coview",
            connector="anthropic",
            model=cfg["model"],
            prompt="",
            mode="A",
            system_prompt=system,
            messages=messages,
            tools=TOOLS,
            max_tokens=cfg["max_tokens"],
            effort=cfg["effort"],
        )

        turn_text = (result.get("body") or "").strip()
        if turn_text:
            full_text_accum.append(turn_text)
            await _emit_stream_text(broadcast, stream_id, turn_text)

        tool_uses = result.get("tool_calls") or []

        if result.get("stop_reason") != "tool_use" or not tool_uses:
            # Done — finalize the stream bubble
            full_text = "\n\n".join(full_text_accum)
            await broadcast({
                "action": "note_stream_done",
                "stream_id": stream_id,
                "text": full_text,
                "owner": "claude",
            })
            if full_text:
                note = {
                    "action": "note",
                    "text": full_text,
                    "owner": "claude",
                    "time": datetime.now().strftime("%H:%M:%S"),
                }
                state["notes"].append(note)
                coview_db.save_note(session_id, note)
            return

        # Execute tools, append results, continue the loop
        messages.append(
            result.get("assistant_message")
            or {"role": "assistant", "content": [{"type": "text", "text": turn_text}]}
        )

        tool_results_content: list[dict] = []
        for tu in tool_uses:
            await broadcast({
                "action": "status",
                "text": f"using {tu.get('name', '')}({json.dumps(tu.get('input') or {})[:120]})",
                "owner": "claude",
            })
            result, is_error = await _execute_tool(
                tu.get("name", ""), tu.get("input") or {}, session_id, state, broadcast
            )
            tool_results_content.append({
                "type": "tool_result",
                "tool_use_id": tu.get("id", ""),
                "content": result,
                "is_error": is_error,
            })

        messages.append({"role": "user", "content": tool_results_content})
        # Fresh bubble for the next text turn (so tool-separated replies read as distinct)
        stream_id = uuid.uuid4().hex[:8]

    # Hit the tool-loop cap
    await broadcast({
        "action": "note",
        "text": "[system] tool-loop cap reached — stopping.",
        "owner": "system",
    })
