"""
AI Governance REST API — /governance 頁面後端
============================================
PR 1：3 個 GET endpoint，供前端 /governance 頁面使用。

Endpoints:
  GET /api/v1/ai/governance/events   — ai_governance_events 查詢（分頁 + 多維度過濾）
  GET /api/v1/ai/governance/queue    — remediation dispatch 隊列（graceful fallback）
  GET /api/v1/ai/governance/summary  — 30d SLO 違反時序 + compliance_rate

設計原則:
- Router 層只負責 HTTP 路由，業務邏輯/DB 查詢在 governance_query_service
- Pydantic V2 response models（src/models/governance.py）
- queue endpoint 在 dispatch 表尚未建立時回 table_pending=True，不拋 500

2026-05-02 ogt + Claude Sonnet 4.6 Asia/Taipei
"""

from __future__ import annotations

from datetime import datetime
from typing import Annotated

import structlog
from fastapi import APIRouter, Query

from src.models.governance import (
    GovernanceEventsResponse,
    GovernanceQueueResponse,
    GovernanceSummaryResponse,
)
from src.services.governance_query_service import (
    query_governance_events,
    query_governance_queue,
    query_governance_summary,
)

logger = structlog.get_logger(__name__)

router = APIRouter()


# =============================================================================
# GET /api/v1/ai/governance/events
# =============================================================================

@router.get("/ai/governance/events", response_model=GovernanceEventsResponse)
async def get_governance_events(
    event_type: Annotated[list[str] | None, Query(alias="event_type")] = None,
    from_: Annotated[datetime | None, Query(alias="from")] = None,
    to: Annotated[datetime | None, Query(alias="to")] = None,
    status: Annotated[str | None, Query(pattern="^(resolved|unresolved)$")] = None,
    severity: Annotated[str | None, Query(pattern="^(critical|warning|info)$")] = None,
    page: Annotated[int, Query(ge=1)] = 1,
    size: Annotated[int, Query(ge=10, le=100)] = 20,
) -> GovernanceEventsResponse:
    """
    查詢 AI 治理事件列表（分頁）。

    - event_type: 多值過濾（可重複傳）
    - from / to: ISO 8601 時間範圍（URL 傳 from 參數）
    - status: resolved / unresolved
    - severity: critical / warning / info（由 event_type 映射決定）
    - page: ≥1，default 1
    - size: 10-100，default 20
    """
    logger.debug(
        "governance_events_request",
        event_types=event_type,
        from_=from_,
        to=to,
        status=status,
        severity=severity,
        page=page,
        size=size,
    )
    return await query_governance_events(
        event_types=event_type,
        from_dt=from_,
        to_dt=to,
        status=status,
        severity=severity,
        page=page,
        size=size,
    )


# =============================================================================
# GET /api/v1/ai/governance/queue
# =============================================================================

@router.get("/ai/governance/queue", response_model=GovernanceQueueResponse)
async def get_governance_queue(
    dispatch_status: Annotated[
        str,
        Query(pattern="^(pending|dispatched|succeeded|failed)$"),
    ] = "pending",
    page: Annotated[int, Query(ge=1)] = 1,
    size: Annotated[int, Query(ge=10, le=100)] = 20,
) -> GovernanceQueueResponse:
    """
    查詢 remediation dispatch 隊列。

    governance_remediation_dispatch 表由 Track D 建立，尚未完成時
    本 endpoint 回傳 { table_pending: true, items: [], total: 0 }，不拋 500。

    - dispatch_status: pending（default）/ dispatched / succeeded / failed
    - page / size: 分頁
    """
    logger.debug(
        "governance_queue_request",
        dispatch_status=dispatch_status,
        page=page,
        size=size,
    )
    return await query_governance_queue(
        dispatch_status=dispatch_status,
        page=page,
        size=size,
    )


# =============================================================================
# GET /api/v1/ai/governance/summary
# =============================================================================

@router.get("/ai/governance/summary", response_model=GovernanceSummaryResponse)
async def get_governance_summary(
    days: Annotated[int, Query(ge=1, le=90)] = 30,
) -> GovernanceSummaryResponse:
    """
    SLO 合規統計摘要（給 /governance SLO tab 使用）。

    - days: 統計天數（1-90，default 30）
    - compliance_rate: 1 - unresolved_count / total_events（total=0 時回 1.0）
    - daily_counts: 每日分類計數時序
    """
    logger.debug("governance_summary_request", days=days)
    return await query_governance_summary(days=days)
