"""admin 比价记录 debug:按 user_id / phone 查列表 + 单条详情(含 LLM 每次调用明细 / 原始 payload)。

只读。读权限默认即可(get_current_admin),不额外 require_role(查记录是基础 debug 能力)。
trace_url 无条件下发——admin 是内部 debug 工具,不走 C 端 user.debug_trace_enabled 权限闸。
"""
from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, Query

from app.admin.deps import AdminDb, get_current_admin
from app.admin.repositories import queries
from app.admin.schemas.common import CursorPage
from app.admin.schemas.comparison import AdminComparisonDetail, AdminComparisonListItem

router = APIRouter(
    prefix="/admin/api/comparison-records",
    tags=["admin-comparison"],
    dependencies=[Depends(get_current_admin)],
)


@router.get(
    "",
    response_model=CursorPage[AdminComparisonListItem],
    summary="比价记录列表(按 user_id/phone 筛 + 分页)",
)
def list_comparison_records(
    db: AdminDb,
    user_id: Annotated[int | None, Query()] = None,
    phone: Annotated[str | None, Query(description="手机号前缀")] = None,
    status: Annotated[str | None, Query(pattern="^(success|failed|cancelled)$")] = None,
    business_type: Annotated[str | None, Query()] = None,
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
    cursor: Annotated[int | None, Query()] = None,
) -> CursorPage[AdminComparisonListItem]:
    items, next_cursor, total = queries.list_comparison_records(
        db, user_id=user_id, phone=phone, status=status,
        business_type=business_type, limit=limit, cursor=cursor,
    )
    return CursorPage(
        items=[AdminComparisonListItem.model_validate(r) for r in items],
        next_cursor=next_cursor,
        total=total,
    )


@router.get(
    "/{record_id}",
    response_model=AdminComparisonDetail,
    summary="比价记录详情(含 LLM 每次调用明细 + 原始 payload)",
)
def get_comparison_record(record_id: int, db: AdminDb) -> AdminComparisonDetail:
    rec = queries.get_comparison_record(db, record_id)
    if rec is None:
        raise HTTPException(status_code=404, detail="记录不存在")
    return AdminComparisonDetail.model_validate(rec)
