"""Traces 라우트 — 트레이스 목록 및 상세."""

import logging

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

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


@router.get("/traces", response_class=HTMLResponse)
async def page_traces(
    request: Request,
    name: str = Query("", alias="name"),
    user_id: str = Query("", alias="user_id"),
    session_id: str = Query("", alias="session_id"),
    from_ts: str = Query("", alias="from"),
    to_ts: str = Query("", alias="to"),
    page: int = Query(1, ge=1),
    limit: int = Query(20, ge=1, le=100),
):
    """Trace 목록 페이지."""
    gw = request.app.state.services.gateway
    traces = []
    api_error = ""

    try:
        traces = gw.list_traces(
            limit=limit,
            name=name or None,
            user_id=user_id or None,
            session_id=session_id or None,
            from_timestamp=from_ts or None,
            to_timestamp=to_ts or None,
            page=page,
        )
    except Exception as e:
        logger.exception("Trace 목록 조회 실패")
        api_error = f"Langfuse API 오류: {e}"

    return request.app.state.templates.TemplateResponse(request, "traces.html", {
        "traces": traces,
        "trace_count": len(traces),
        "active_page": "traces",
        "api_error": api_error,
        "filters": {
            "name": name,
            "user_id": user_id,
            "session_id": session_id,
            "from": from_ts,
            "to": to_ts,
        },
        "page": page,
        "limit": limit,
    })


@router.get("/traces/{trace_id}", response_class=HTMLResponse)
async def page_trace_detail(request: Request, trace_id: str):
    """Trace 상세 페이지 + Copilot context 자동 주입."""
    gw = request.app.state.services.gateway
    trace = None
    api_error = ""

    try:
        trace = gw.get_trace(trace_id)
    except Exception as e:
        logger.exception("Trace 상세 조회 실패: %s", trace_id)
        api_error = f"Langfuse API 오류: {e}"

    copilot_context = {
        "surface_type": "trace",
        "object_id": trace_id,
        "object_metadata": {
            "name": trace.get("name") if trace else "",
            "level": trace.get("level") if trace else "",
            "latency": trace.get("latency") if trace else None,
            "cost": trace.get("total_cost") if trace else None,
        },
    }

    return request.app.state.templates.TemplateResponse(request, "trace_detail.html", {
        "trace": trace,
        "trace_id": trace_id,
        "active_page": "traces",
        "api_error": api_error,
        "copilot_context": copilot_context,
    })
