"""
Audit Log API Endpoints (Phase 4)
==================================
Action Log 稽核日誌 API

Endpoints:
- GET  /api/v1/audit-logs           - 取得稽核日誌清單
- GET  /api/v1/audit-logs/{id}      - 取得單筆稽核日誌
- GET  /api/v1/audit-logs/stats     - 統計資訊

提供 K8s 操作執行的完整審計軌跡。
"""

from typing import Any

from fastapi import APIRouter, HTTPException, Query, status
from pydantic import BaseModel

from src.core.logging import get_logger
from src.db.models import AuditLog
from src.services.audit_log_service import get_audit_log_service

router = APIRouter(prefix="/audit-logs", tags=["Audit Logs"])
logger = get_logger("awoooi.audit")


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

class AuditLogResponse(BaseModel):
    """單筆稽核日誌回應"""
    id: str
    approval_id: str
    operation_type: str
    target_resource: str
    namespace: str
    success: bool
    error_message: str | None
    k8s_response: dict[str, Any] | None
    executed_by: str
    execution_duration_ms: int | None
    dry_run_passed: bool
    dry_run_message: str | None
    created_at: str
    # Phase 18: 失敗自動修復閉環欄位
    authorization_channel: str | None = None
    retry_count: int = 0
    failure_classification: str | None = None
    source_approval_id: str | None = None
    auto_repair_attempted: bool = False
    auto_repair_result: str | None = None


class AuditLogListResponse(BaseModel):
    """稽核日誌清單回應"""
    count: int
    logs: list[AuditLogResponse]
    page: int
    page_size: int
    total_pages: int


class AuditStatsResponse(BaseModel):
    """稽核統計回應"""
    total_executions: int
    success_count: int
    failure_count: int
    success_rate: float
    avg_duration_ms: float | None
    by_operation_type: dict[str, int]
    by_namespace: dict[str, int]
    last_24h_count: int


# =============================================================================
# Helper Functions
# =============================================================================

def audit_log_to_response(log: AuditLog) -> AuditLogResponse:
    """Convert DB AuditLog to response model"""
    return AuditLogResponse(
        id=log.id,
        approval_id=log.approval_id,
        operation_type=log.operation_type,
        target_resource=log.target_resource,
        namespace=log.namespace,
        success=log.success,
        error_message=log.error_message,
        k8s_response=log.k8s_response,
        executed_by=log.executed_by,
        execution_duration_ms=log.execution_duration_ms,
        dry_run_passed=log.dry_run_passed,
        dry_run_message=log.dry_run_message,
        created_at=log.created_at.isoformat() if log.created_at else "",
        # Phase 18: 失敗自動修復閉環欄位
        authorization_channel=log.authorization_channel,
        retry_count=log.retry_count or 0,
        failure_classification=log.failure_classification,
        source_approval_id=log.source_approval_id,
        auto_repair_attempted=log.auto_repair_attempted or False,
        auto_repair_result=log.auto_repair_result,
    )


# =============================================================================
# GET /api/v1/audit-logs
# =============================================================================

@router.get(
    "",
    response_model=AuditLogListResponse,
    summary="取得稽核日誌清單",
    description="分頁取得 K8s 操作執行的稽核日誌，支援篩選條件",
)
async def list_audit_logs(
    page: int = Query(default=1, ge=1, description="頁碼"),
    page_size: int = Query(default=20, ge=1, le=100, description="每頁筆數"),
    success: bool | None = Query(default=None, description="篩選成功/失敗"),
    operation_type: str | None = Query(default=None, description="篩選操作類型"),
    namespace: str | None = Query(default=None, description="篩選 Namespace"),
) -> AuditLogListResponse:
    """
    取得稽核日誌清單

    支援分頁與篩選：
    - page: 頁碼 (從 1 開始)
    - page_size: 每頁筆數 (預設 20，最大 100)
    - success: 篩選成功/失敗
    - operation_type: 篩選操作類型 (e.g., DELETE_POD)
    - namespace: 篩選 Namespace

    Returns:
        AuditLogListResponse: 分頁稽核日誌
    """
    # Phase 22 P1: Router 層違規修復 - 改用 Service 層 (2026-03-31)
    service = get_audit_log_service()

    logs, total_count = await service.list_logs(
        page=page,
        page_size=page_size,
        success_only=success,
        namespace=namespace,
        operation_type=operation_type,
    )
    total_pages = (total_count + page_size - 1) // page_size if total_count > 0 else 1

    logger.info(
        "audit_logs_listed",
        count=len(logs),
        page=page,
        total=total_count,
    )

    return AuditLogListResponse(
        count=total_count,
        logs=[audit_log_to_response(log) for log in logs],
        page=page,
        page_size=page_size,
        total_pages=total_pages,
    )


# =============================================================================
# GET /api/v1/audit-logs/stats
# =============================================================================

@router.get(
    "/stats",
    response_model=AuditStatsResponse,
    summary="取得稽核統計",
    description="取得操作執行的統計資訊",
)
async def get_audit_stats() -> AuditStatsResponse:
    """
    取得稽核統計資訊

    包含：
    - 總執行數
    - 成功/失敗數
    - 成功率
    - 平均執行時間
    - 按操作類型分組統計
    - 按 Namespace 分組統計
    - 過去 24 小時執行數

    Returns:
        AuditStatsResponse: 統計資訊
    """
    # Phase 22 P1: Router 層違規修復 - 改用 Service 層 (2026-03-31)
    service = get_audit_log_service()
    stats = await service.get_stats(since_hours=24)

    logger.info(
        "audit_stats_fetched",
        total=stats["total"],
        success_rate=stats["success_rate"],
    )

    return AuditStatsResponse(
        total_executions=stats["total"],
        success_count=stats["success_count"],
        failure_count=stats["failure_count"],
        success_rate=stats["success_rate"],
        avg_duration_ms=stats["avg_duration_ms"],
        by_operation_type=stats["by_operation_type"],
        by_namespace=stats["by_namespace"],
        last_24h_count=stats["last_24h_count"],
    )


# =============================================================================
# GET /api/v1/audit-logs/{id}
# =============================================================================

@router.get(
    "/{log_id}",
    response_model=AuditLogResponse,
    summary="取得單筆稽核日誌",
    description="根據 ID 取得稽核日誌詳情",
)
async def get_audit_log(log_id: str) -> AuditLogResponse:
    """
    取得單筆稽核日誌

    Args:
        log_id: 稽核日誌 ID

    Returns:
        AuditLogResponse: 稽核日誌詳情

    Raises:
        HTTPException: 404 找不到日誌
    """
    # Phase 22 P1: Router 層違規修復 - 改用 Service 層 (2026-03-31)
    service = get_audit_log_service()
    log = await service.get_by_id(log_id)

    if log is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Audit log not found",
        )

    logger.info(
        "audit_log_fetched",
        log_id=log_id,
    )

    return audit_log_to_response(log)
