"""AwoooP Operator Console — truth-chain read API."""

from __future__ import annotations

from time import perf_counter
from typing import Any

from fastapi import APIRouter, Depends, Query

from src.core.awooop_operator_auth import (
    AwoooPOperatorPrincipal,
    verify_awooop_operator,
)
from src.services.awooop_truth_chain_service import (
    fetch_automation_quality_summary,
    fetch_truth_chain,
    record_quality_summary_observation,
)

router = APIRouter()


@router.get(
    "/truth-chain/quality/summary",
    summary="查詢 AI 自動化品質總覽",
    description=(
        "T12c read-only aggregate endpoint. 聚合最近 incident 的 automation quality gate，"
        "讓 Operator 不必逐張 Telegram 卡片判斷是否真正完成 AI 自動修復。"
        "此總覽不回傳逐筆 examples；source-level truth-chain 詳情仍需 operator auth。"
    ),
)
async def get_automation_quality_summary(
    project_id: str = Query("awoooi", description="租戶 ID"),
    hours: int = Query(24, ge=1, le=168, description="回看小時數"),
    limit: int = Query(200, ge=1, le=500, description="最多評估 incident 數"),
    refresh: bool = Query(False, description="略過短 TTL 快取並重新聚合"),
) -> dict[str, Any]:
    started_at = perf_counter()
    try:
        summary = await fetch_automation_quality_summary(
            project_id=project_id,
            hours=hours,
            limit=limit,
            refresh=refresh,
        )
    except Exception as exc:
        record_quality_summary_observation(
            project_id=project_id,
            hours=hours,
            limit=limit,
            cache_status="error",
            success=False,
            duration_seconds=perf_counter() - started_at,
            error=exc.__class__.__name__,
        )
        raise
    summary["examples"] = []
    summary["visibility_note"] = (
        "Aggregate only. Use /truth-chain/{source_id} with operator auth for source-level details."
    )
    return summary


@router.get(
    "/truth-chain/{source_id}",
    summary="查詢 Telegram / Incident / Drift 真相鏈",
    description=(
        "T0 read-only endpoint. 聚合 incident、approval、evidence、MCP、"
        "automation_operation_log、drift repeat state 與 outbound mirror，"
        "讓 Operator Console 能判斷 Telegram 卡片目前卡在哪個流程節點。"
    ),
)
async def get_truth_chain(
    source_id: str,
    project_id: str = Query("awoooi", description="租戶 ID"),
    operator: AwoooPOperatorPrincipal = Depends(verify_awooop_operator),
) -> dict[str, Any]:
    # operator dependency intentionally gates this read API even though the
    # principal is not otherwise needed by the aggregation query.
    _ = operator
    return await fetch_truth_chain(source_id=source_id, project_id=project_id)
