"""
Metrics API - 黃金指標端點 (Gold Metrics Endpoint)
===================================================
Phase 17 重構: Router 層只做 HTTP 轉發，業務邏輯移至 Service 層

統帥鐵律: 禁止假數據！所有指標必須來自 SignOz 真實血脈

Endpoints:
- GET /metrics/gold - 獲取 Gold Metrics (RPS, Error Rate, P99, AI Success)
- GET /metrics/health - Metrics 子系統健康檢查

架構層次:
- Router (此檔案) → MetricsService → MetricsRepository → PostgreSQL
- Router (此檔案) → MetricsService → SignOzClient → ClickHouse

版本: v2.0
更新: 2026-03-26 (台北時區)
更新者: Claude Code (Phase 17 技術債修復 - Router 層違規抽取)
原版: v1.0 by Claude Code
"""

from datetime import datetime
from typing import Any

from fastapi import APIRouter
from pydantic import BaseModel

from src.core.logging import get_logger
from src.services.metrics_service import get_metrics_service

logger = get_logger("awoooi.metrics")
router = APIRouter()


# =============================================================================
# Response Models
# =============================================================================


class TrendData(BaseModel):
    """Sparkline 趨勢數據"""

    values: list[float]
    direction: str  # up, down, stable


class GoldMetricItem(BaseModel):
    """單一黃金指標"""

    label: str
    value: float | str
    unit: str | None = None
    trend: list[float]
    status: str  # healthy, warning, critical


class GoldMetricsResponse(BaseModel):
    """Gold Metrics API Response"""

    timestamp: datetime
    service_name: str
    metrics: list[GoldMetricItem]
    raw_data: dict[str, Any] | None = None


# =============================================================================
# Endpoints
# =============================================================================


@router.get("/metrics/gold", response_model=GoldMetricsResponse)
async def get_gold_metrics(
    service_name: str = "awoooi-api",
    time_window_minutes: int = 10,
) -> GoldMetricsResponse:
    """
    獲取黃金指標 (Gold Metrics)

    統帥鐵律:
    - 所有數據必須來自 SignOz 真實血脈
    - AI Success 來自 AuditLog 真實統計
    - 無數據時顯示 0，嚴禁造假

    Returns:
        GoldMetricsResponse with RPS, Error Rate, P99, AI Success
    """
    logger.info(
        "gold_metrics_request",
        service=service_name,
        window_minutes=time_window_minutes,
    )

    # 透過 Service 取得數據
    service = get_metrics_service()
    result = await service.get_gold_metrics(
        service_name=service_name,
        time_window_minutes=time_window_minutes,
    )

    # 轉換為 Response Model
    metrics_list = [
        GoldMetricItem(
            label=m.label,
            value=m.value,
            unit=m.unit,
            trend=m.trend,
            status=m.status,
        )
        for m in result.metrics
    ]

    return GoldMetricsResponse(
        timestamp=result.timestamp,
        service_name=result.service_name,
        metrics=metrics_list,
        raw_data=result.raw_data,
    )


@router.get("/metrics/health")
async def metrics_health() -> dict:
    """
    Metrics 子系統健康檢查

    快速檢查 SignOz 連線狀態
    """
    service = get_metrics_service()
    return await service.check_health()
