"""按 trace_id 同机拉 pricebot 的本次比价 LLM 调用明细(供 admin 比价记录 debug)。

pricebot 在 chat() 收口处把每次 LLM input/output 落盘,暴露内部接口
GET /api/internal/llm_calls/{trace_id}(X-Internal-Secret 校验,与本服务 INTERNAL_API_SECRET 同值)。
app-server 收到比价记录上报后同机拉一次,落 comparison_record.llm_calls。

best-effort:拉不到(pricebot 未部署该版本 / 旧 trace 无明细 / 网络)一律返 [],绝不阻断
比价记录上报。多实例下用 pick_pricebot(trace_id) 选对实例(同 trace 落同进程,明细在
该进程磁盘),与比价透传同一致性 hash 口径。
"""
from __future__ import annotations

import logging

import httpx

from app.core.config import settings
from app.core.pricebot_router import pick_pricebot

logger = logging.getLogger("shagua.pricebot_llm")


def pricebot_llm_auth_ready() -> bool:
    """Verify every configured PriceBot instance accepts the shared secret."""
    secret = settings.INTERNAL_API_SECRET
    if not secret:
        logger.error("PriceBot LLM auth check failed: INTERNAL_API_SECRET is empty")
        return False
    for base in settings.pricebot_instances:
        url = f"{base.rstrip('/')}/api/internal/llm_calls/__auth_probe__"
        try:
            resp = httpx.get(
                url, headers={"X-Internal-Secret": secret}, timeout=3.0
            )
        except Exception as exc:  # noqa: BLE001
            logger.error("PriceBot LLM auth check unavailable base=%s: %s", base, exc)
            return False
        if resp.status_code != 200:
            logger.error(
                "PriceBot LLM auth check rejected base=%s status=%s; "
                "verify both services use the same INTERNAL_API_SECRET",
                base,
                resp.status_code,
            )
            return False
    return True


def fetch_llm_calls(trace_id: str) -> list[dict]:
    """返回该次比价的 LLM 调用明细列表(每条 {scene,model,input_messages,output,usage,latency_ms,error});
    未配密钥 / 无 trace_id / 拉取失败 → []。"""
    secret = settings.INTERNAL_API_SECRET
    if not secret or not trace_id:
        return []
    preferred = pick_pricebot(trace_id)
    # LLM JSONL is instance-local. If the cluster topology changed after a
    # historical trace was created, consistent hashing may now point elsewhere;
    # probe the remaining configured instances only when the preferred one is empty.
    bases = [preferred, *(base for base in settings.pricebot_instances if base != preferred)]
    for base in bases:
        url = f"{base.rstrip('/')}/api/internal/llm_calls/{trace_id}"
        try:
            resp = httpx.get(url, headers={"X-Internal-Secret": secret}, timeout=5.0)
            if resp.status_code == 200:
                calls = resp.json().get("calls", []) or []
                if calls:
                    return calls
                continue
            if resp.status_code in (401, 403):
                logger.error(
                    "fetch_llm_calls rejected trace=%s base=%s status=%s; "
                    "INTERNAL_API_SECRET differs between app-server and PriceBot",
                    trace_id,
                    base,
                    resp.status_code,
                )
            else:
                logger.warning(
                    "fetch_llm_calls trace=%s base=%s status=%s",
                    trace_id,
                    base,
                    resp.status_code,
                )
        except Exception as e:  # noqa: BLE001 — best-effort
            logger.warning("fetch_llm_calls trace=%s base=%s failed: %s", trace_id, base, e)
    return []
