"""Chat @ mention suggest API."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Literal

from fastapi import APIRouter, HTTPException, Query, Request

from niannian.brain.cerebellum.wiki_search import WikiSearch
from niannian.tenant.context import resolve_request_context
from niannian.vault.search import VaultSearchService
from niannian.vault.store import VaultStore

if TYPE_CHECKING:
    from niannian.client import NianNian

MentionKind = Literal["vault", "wiki"]


def create_chat_mentions_router(nn: NianNian) -> APIRouter:
    router = APIRouter(prefix="/v1/chat", tags=["chat"])

    @router.get("/mentions/suggest")
    def mention_suggest(
        request: Request,
        q: str = Query(""),
        kind: MentionKind = Query("vault"),
        limit: int = Query(8, ge=1, le=20),
    ) -> dict[str, Any]:
        resolve_request_context(request, nn._config, home=nn._home)
        query = (q or "").strip()
        if kind == "vault":
            store = VaultStore(
                nn._home,
                manifest=getattr(nn._store, "manifest", None),
                config=nn._config,
            )
            hits = VaultSearchService(store, config=nn._config).search(query, limit=limit)
            items = [
                {
                    "id": str(h.get("vault_id") or ""),
                    "title": str(h.get("title") or h.get("vault_id") or ""),
                    "snippet": str(h.get("snippet") or "")[:120],
                }
                for h in hits
                if isinstance(h, dict)
            ]
            return {"kind": kind, "query": query, "items": items}

        if kind == "wiki":
            wiki = WikiSearch(nn._store, graph_bfs_enabled=False)
            hits = wiki.search(query, limit=limit)
            items = [
                {
                    "id": str(getattr(h, "page_id", "") or ""),
                    "title": str(getattr(h, "title", "") or getattr(h, "page_id", "") or ""),
                    "snippet": str(getattr(h, "summary", "") or "")[:120],
                }
                for h in hits
            ]
            return {"kind": kind, "query": query, "items": items}

        raise HTTPException(status_code=400, detail={"code": "invalid_kind"})

    return router
