"""Vault search API endpoint."""

from __future__ import annotations

from fastapi import APIRouter, Request

router = APIRouter(prefix="/search", tags=["search"])


@router.get("")
async def search_vault(request: Request, q: str, limit: int = 10) -> list[dict]:
    """Search vault content via FTS5."""
    vault_search = request.app.state.vault_search
    return await vault_search.search(q, limit=limit)


@router.get("/semantic")
async def semantic_search(request: Request, q: str, limit: int = 10) -> list[dict]:
    """Semantic search via vector embeddings (Ollama `/api/embed`).

    When Ollama isn't running OR the embedding model (`bge-m3` by default)
    isn't pulled, degrades to keyword-only FTS5 so callers don't see 5xx.
    The precise reason is surfaced by ``vault_embeddings.health()`` for
    the capability-indicator UI to read.
    """
    from agntspace.vault.embeddings import EmbeddingsUnavailable

    embeddings = getattr(request.app.state, "vault_embeddings", None)
    if not embeddings:
        return []
    try:
        return await embeddings.search(q, limit=limit)
    except EmbeddingsUnavailable:
        vault_search = getattr(request.app.state, "vault_search", None)
        if vault_search is None:
            return []
        return await vault_search.search(q, limit=limit)


@router.get("/hybrid")
async def hybrid_search(request: Request, q: str, limit: int = 10) -> list[dict]:
    """Hybrid search: 70% semantic + 30% keyword, with graceful FTS-only fallback.

    Falls back to keyword-only in two cases:
      1. `vault_embeddings` isn't wired (fresh vault before first index).
      2. Ollama isn't reachable OR the embedding model isn't pulled — the
         hybrid endpoint silently downgrades to FTS5 so best-effort callers
         (e.g. the chat related-notes sidebar) keep working.
    """
    from agntspace.vault.embeddings import EmbeddingsUnavailable

    embeddings = getattr(request.app.state, "vault_embeddings", None)
    vault_search = getattr(request.app.state, "vault_search", None)
    if not embeddings:
        if vault_search is None:
            return []
        return await vault_search.search(q, limit=limit)
    try:
        return await embeddings.hybrid_search(q, limit=limit)
    except EmbeddingsUnavailable:
        if vault_search is None:
            return []
        return await vault_search.search(q, limit=limit)


@router.post("/reindex")
async def reindex(request: Request) -> dict:
    """Rebuild the vault search index (FTS5 + embeddings)."""
    vault_search = request.app.state.vault_search
    fts_count = await vault_search.index_vault()

    emb_count = 0
    embeddings = getattr(request.app.state, "vault_embeddings", None)
    if embeddings:
        emb_count = await embeddings.index_vault()

    return {"fts_indexed": fts_count, "embeddings_indexed": emb_count}
