"""
Audit Log API

操作审计日志 API 端点。
"""

import logging
from typing import Optional, Dict, Any, List
from datetime import datetime
from fastapi import APIRouter, Depends, Query, Request
from pydantic import BaseModel, Field

from src.auth.dependencies import require_admin
from src.auth.models import UserAuth
from src.models.schemas import ResponseModel
from src.utils.pagination import Paginator
from src.services.audit_log_service import audit_log_service
from src.models.audit_log import AuditLogDB
from src.utils.errors import ErrorCode, AppException

router = APIRouter(prefix="/admin/audit-logs", tags=["admin-audit-logs"])
logger = logging.getLogger(__name__)


# ===== 响应模型 =====

class AuditLogListItem(BaseModel):
    """审计日志列表项"""
    id: str
    user_id: Optional[str]
    username: Optional[str]
    action: str
    resource_type: Optional[str]
    resource_id: Optional[str]
    ip_address: Optional[str]
    created_at: str  # ISO format


class AuditLogDetailResponse(BaseModel):
    """审计日志详情"""
    id: str
    user_id: Optional[str]
    username: Optional[str]
    action: str
    resource_type: Optional[str]
    resource_id: Optional[str]
    ip_address: Optional[str]
    user_agent: Optional[str]
    details: Optional[Dict[str, Any]]
    created_at: str


# ===== API 端点 =====

@router.get("", response_model=ResponseModel)
async def list_audit_logs(
    request: Request,
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    user_id: Optional[str] = Query(None, description="按用户 ID 过滤"),
    action: Optional[str] = Query(None, description="按操作类型过滤"),
    resource_type: Optional[str] = Query(None, description="按资源类型过滤"),
    resource_id: Optional[str] = Query(None, description="按资源 ID 过滤"),
    start_date: Optional[str] = Query(None, description="开始日期 (ISO format)"),
    end_date: Optional[str] = Query(None, description="结束日期 (ISO format)"),
    sort_by: str = Query("created_at", description="排序字段"),
    sort_order: str = Query("desc", description="排序方向"),
    current_user: UserAuth = Depends(require_admin),
):
    """
    列出审计日志

    支持高级搜索：按用户、操作类型、资源类型、时间范围过滤。
    需要管理员权限。
    """
    try:
        # 构建过滤条件
        filters = {}
        if user_id:
            filters["user_id"] = user_id
        if action:
            filters["action"] = action
        if resource_type:
            filters["resource_type"] = resource_type
        if resource_id:
            filters["resource_id"] = resource_id
        if start_date:
            filters["start_date"] = start_date
        if end_date:
            filters["end_date"] = end_date

        logs, total = audit_log_service.list_logs(
            page=page,
            page_size=page_size,
            filters=filters,
            sort_by=sort_by,
            sort_order=sort_order,
        )

        # 转换为响应格式
        items = [
            AuditLogListItem(
                id=log.id,
                user_id=log.user_id,
                username=log.username,
                action=log.action,
                resource_type=log.resource_type,
                resource_id=log.resource_id,
                ip_address=log.ip_address,
                created_at=datetime.fromtimestamp(log.created_at).isoformat(),
            ).model_dump()
            for log in logs
        ]

        paginator = Paginator(
            items=items,
            total=total,
            page=page,
            page_size=page_size,
        )

        return paginator.to_response(request)
    except Exception as e:
        logger.error(f"Error listing audit logs: {e}")
        raise


@router.get("/{log_id}", response_model=ResponseModel)
async def get_audit_log(
    log_id: str,
    current_user: UserAuth = Depends(require_admin),
):
    """
    获取审计日志详情

    需要管理员权限。
    """
    try:
        log = audit_log_service.get_log(log_id)
        if not log:
            raise AppException(
                message="Audit log not found",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )

        return ResponseModel(
            data=AuditLogDetailResponse(
                id=log.id,
                user_id=log.user_id,
                username=log.username,
                action=log.action,
                resource_type=log.resource_type,
                resource_id=log.resource_id,
                ip_address=log.ip_address,
                user_agent=log.user_agent,
                details=log.details,
                created_at=datetime.fromtimestamp(log.created_at).isoformat(),
            ).model_dump()
        )
    except AppException:
        raise
    except Exception as e:
        logger.error(f"Error getting audit log: {e}")
        raise


@router.get("/export/csv", response_model=ResponseModel)
async def export_audit_logs(
    user_id: Optional[str] = Query(None, description="按用户 ID 过滤"),
    action: Optional[str] = Query(None, description="按操作类型过滤"),
    resource_type: Optional[str] = Query(None, description="按资源类型过滤"),
    start_date: Optional[str] = Query(None, description="开始日期 (ISO format)"),
    end_date: Optional[str] = Query(None, description="结束日期 (ISO format)"),
    current_user: UserAuth = Depends(require_admin),
):
    """
    导出审计日志为 CSV

    需要管理员权限。
    """
    try:
        # 构建过滤条件
        filters = {}
        if user_id:
            filters["user_id"] = user_id
        if action:
            filters["action"] = action
        if resource_type:
            filters["resource_type"] = resource_type
        if start_date:
            filters["start_date"] = start_date
        if end_date:
            filters["end_date"] = end_date

        csv_content = audit_log_service.export_logs(filters=filters)

        return ResponseModel(
            data={
                "content": csv_content,
                "filename": f"audit_logs_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
            }
        )
    except Exception as e:
        logger.error(f"Error exporting audit logs: {e}")
        raise
