"""
Alert Operation Log API Endpoints
==================================
告警操作日誌 API — 提供 alert_operation_log 的查詢介面

Endpoints:
- GET  /api/v1/alert-operation-logs         - 分頁列表（最新優先）
- GET  /api/v1/alert-operation-logs/stats   - 統計（24h 事件分佈）

2026-04-09 Claude Sonnet 4.6 Asia/Taipei (Sprint 5.2)
"""

from typing import Any

from fastapi import APIRouter, Query
from pydantic import BaseModel

from src.core.logging import get_logger
from src.repositories.alert_operation_log_repository import get_alert_operation_log_repository

router = APIRouter(prefix="/alert-operation-logs", tags=["Alert Operation Logs"])
logger = get_logger("awoooi.alert_op_log")


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

class AlertOperationLogResponse(BaseModel):
    id: str
    incident_id: str | None
    approval_id: str | None
    audit_log_id: str | None
    auto_repair_id: str | None
    event_type: str
    actor: str | None
    action_detail: str | None
    success: bool | None
    error_message: str | None
    context: dict[str, Any]
    created_at: str

    model_config = {"from_attributes": True}


class AlertOperationLogListResponse(BaseModel):
    items: list[AlertOperationLogResponse]
    total: int
    limit: int
    offset: int


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

@router.get("/stats", summary="取得告警操作事件統計")
async def get_stats(
    since_hours: int = Query(default=24, ge=1, le=168),
) -> dict[str, Any]:
    repo = get_alert_operation_log_repository()
    return await repo.get_stats(since_hours=since_hours)


@router.get("", response_model=AlertOperationLogListResponse, summary="取得告警操作日誌列表")
async def list_logs(
    limit: int = Query(default=50, ge=1, le=200),
    offset: int = Query(default=0, ge=0),
    event_type: str | None = Query(default=None),
    incident_id: str | None = Query(default=None),
) -> AlertOperationLogListResponse:
    repo = get_alert_operation_log_repository()
    items, total = await repo.list_recent(
        limit=limit,
        offset=offset,
        event_type=event_type,
        incident_id=incident_id,
    )
    return AlertOperationLogListResponse(
        items=[
            AlertOperationLogResponse(
                id=str(item.id),
                incident_id=item.incident_id,
                approval_id=item.approval_id,
                audit_log_id=item.audit_log_id,
                auto_repair_id=item.auto_repair_id,
                event_type=str(item.event_type),
                actor=item.actor,
                action_detail=item.action_detail,
                success=item.success,
                error_message=item.error_message,
                context=item.context or {},
                created_at=item.created_at.isoformat(),
            )
            for item in items
        ],
        total=total,
        limit=limit,
        offset=offset,
    )
