"""Prompts 라우트 — 프롬프트 목록 및 상세."""

import logging

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse

import sentinel.config as config

router = APIRouter()
logger = logging.getLogger("sentinel.web.prompts")


@router.get("/prompts", response_class=HTMLResponse)
async def page_prompts(request: Request):
    """Prompt 목록 페이지."""
    prompts = []
    api_error = ""

    try:
        # Langfuse API에서 prompt 목록 조회
        res = config.get_lf_client().api.prompts.list(limit=50)
        data = res.data if hasattr(res, "data") else res
        for p in data:
            prompts.append({
                "name": getattr(p, "name", ""),
                "version": getattr(p, "version", None),
                "labels": getattr(p, "labels", []),
                "type": getattr(p, "type", "text"),
                "updated_at": str(getattr(p, "updated_at", ""))[:19],
            })
    except Exception as e:
        logger.exception("Prompt 목록 조회 실패")
        api_error = f"Langfuse API 오류: {e}"

    return request.app.state.templates.TemplateResponse(request, "prompts.html", {
        "prompts": prompts,
        "prompt_count": len(prompts),
        "active_page": "prompts",
        "api_error": api_error,
    })


@router.get("/prompts/{name}", response_class=HTMLResponse)
async def page_prompt_detail(request: Request, name: str):
    """Prompt 상세 페이지 + Copilot context 주입."""
    gw = request.app.state.services.gateway
    prompt_data = None
    api_error = ""

    try:
        prompt_data = gw.get_prompt(name)
    except Exception as e:
        logger.exception("Prompt 상세 조회 실패: %s", name)
        api_error = f"Langfuse API 오류: {e}"

    copilot_context = {
        "surface_type": "prompt",
        "object_id": name,
        "object_metadata": {
            "version": prompt_data.get("version") if prompt_data else None,
            "label": prompt_data.get("label") if prompt_data else None,
        },
    }

    return request.app.state.templates.TemplateResponse(request, "prompt_detail.html", {
        "prompt": prompt_data,
        "prompt_name": name,
        "active_page": "prompts",
        "api_error": api_error,
        "copilot_context": copilot_context,
    })
