"""
RAG 知識庫 API Router - Phase 33
===================================
leWOOOgo 原則: Router 只做 HTTP 轉發，業務邏輯在 KnowledgeRAGService

版本: v1.0
建立: 2026-04-10 (台北時區)
建立者: Claude Code (Phase 33 ADR-067)
"""

from fastapi import APIRouter, BackgroundTasks
from pydantic import BaseModel

from src.core.config import get_settings
from src.services.knowledge_rag_service import get_knowledge_rag_service

router = APIRouter(prefix="/rag", tags=["RAG Knowledge Base"])


class RagQueryRequest(BaseModel):
    question: str
    top_k: int = 5


class RagQueryResponse(BaseModel):
    answer: str
    question: str


class RagIndexResponse(BaseModel):
    status: str
    message: str


@router.post("/index", response_model=RagIndexResponse, summary="觸發知識庫全量索引")
async def trigger_index(background_tasks: BackgroundTasks) -> RagIndexResponse:
    """
    觸發文件向量化索引（背景執行）

    索引來源：
    - docs/runbooks/*.md
    - docs/adr/*.md
    - docs/LOGBOOK.md
    - .agents/skills/*.md
    """
    background_tasks.add_task(_run_index)
    model = get_settings().OLLAMA_EMBEDDING_MODEL
    return RagIndexResponse(
        status="accepted",
        message=f"索引已排程，背景執行中（{model} @ Ollama GCP-A/GCP-B/111）",
    )


@router.post("/query", response_model=RagQueryResponse, summary="語義查詢知識庫")
async def query_rag(request: RagQueryRequest) -> RagQueryResponse:
    """語義搜尋知識庫，用 deepseek-r1:14b 生成回答"""
    svc = get_knowledge_rag_service()
    answer = await svc.query(request.question, top_k=request.top_k)
    return RagQueryResponse(answer=answer, question=request.question)


@router.get("/debug", summary="RAG 容器環境診斷", include_in_schema=False)
async def rag_debug() -> dict:
    """診斷用：確認容器內 docs 路徑 + Ollama 連線"""
    import os
    from pathlib import Path

    import httpx

    paths_check = {}
    for p in ["docs/runbooks", "docs/adr", "docs", ".agents/skills"]:
        d = Path(p)
        paths_check[p] = {
            "exists": d.exists(),
            "files": [f.name for f in d.glob("*.md")][:3] if d.exists() else [],
        }

    ollama_ok: bool | str = False
    try:
        async with httpx.AsyncClient(timeout=10.0) as c:
            from src.core.config import get_settings as _gs
            from src.services.ollama_endpoint_resolver import resolve_ollama_order

            settings = _gs()
            statuses: list[str] = []
            for endpoint in resolve_ollama_order("embedding"):
                if not endpoint.url:
                    continue
                r = await c.post(
                    f"{endpoint.url}/api/embeddings",
                    json={"model": settings.OLLAMA_EMBEDDING_MODEL, "prompt": "test"},
                )
                if r.status_code == 200:
                    ollama_ok = True
                    break
                statuses.append(f"{endpoint.provider_name}=http_{r.status_code}")
            if ollama_ok is not True:
                ollama_ok = ", ".join(statuses) or "no_endpoint"
    except Exception as e:
        ollama_ok = f"error: {type(e).__name__}: {e}"

    return {"cwd": os.getcwd(), "paths": paths_check, "ollama_embedding": ollama_ok}


@router.get("/stats", summary="索引統計")
async def rag_stats() -> dict:
    """取得知識庫索引統計（chunk 數量等）"""
    svc = get_knowledge_rag_service()
    return await svc.get_stats()


@router.post("/optimize", summary="建立 ivfflat 向量索引（需 >100 chunks）", include_in_schema=False)
async def rag_optimize() -> dict:
    """對 rag_chunks.embedding 建立 ivfflat 索引，加速向量搜尋"""
    import src.repositories.rag_chunk_repository as rag_repo
    return await rag_repo.create_ivfflat_index()


# ============================================================
# Background helper
# ============================================================

async def _run_index() -> None:
    """背景：委派給 KnowledgeRAGService.index_all_sources() 執行"""
    svc = get_knowledge_rag_service()
    await svc.index_all_sources()
