from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, Query, status

from app.api.deps import CurrentUserContext, require_platform_admin_user
from app.schemas.common import ErrorResponse
from app.schemas.system_log import SystemLogEntryRead, SystemLogFileRead, SystemLogTailRead
from app.services.system_logs import SystemLogService

router = APIRouter(prefix="/system-logs")


@router.get(
    "/entries",
    response_model=list[SystemLogEntryRead],
    summary="查询系统日志记录列表",
    description="解析 server/logs 下最近的日志内容，按单条日志记录返回，仅管理员可用。",
    responses={
        status.HTTP_403_FORBIDDEN: {
            "model": ErrorResponse,
            "description": "只有管理员可以查看系统日志。",
        }
    },
)
def list_system_log_entries(
    _: Annotated[CurrentUserContext, Depends(require_platform_admin_user)],
    limit: Annotated[int, Query(ge=20, le=1000, description="返回的日志记录数。")] = 300,
) -> list[SystemLogEntryRead]:
    return SystemLogService().list_entries(entry_limit=limit)


@router.get(
    "/entries/{entry_id}",
    response_model=SystemLogEntryRead,
    summary="读取单条系统日志记录",
    description="按日志记录 ID 返回结构化解析结果，仅管理员可用。",
    responses={
        status.HTTP_403_FORBIDDEN: {
            "model": ErrorResponse,
            "description": "只有管理员可以查看系统日志。",
        },
        status.HTTP_404_NOT_FOUND: {
            "model": ErrorResponse,
            "description": "日志记录不存在。",
        },
    },
)
def get_system_log_entry(
    entry_id: str,
    _: Annotated[CurrentUserContext, Depends(require_platform_admin_user)],
) -> SystemLogEntryRead:
    try:
        return SystemLogService().get_entry(entry_id)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="日志记录不存在。",
        ) from exc


@router.get(
    "/files",
    response_model=list[SystemLogFileRead],
    summary="查询系统日志文件列表",
    description="返回 server/logs 目录下可查看的日志文件列表，仅管理员可用。",
    responses={
        status.HTTP_403_FORBIDDEN: {
            "model": ErrorResponse,
            "description": "只有管理员可以查看系统日志。",
        }
    },
)
def list_system_log_files(
    _: Annotated[CurrentUserContext, Depends(require_platform_admin_user)],
) -> list[SystemLogFileRead]:
    return SystemLogService().list_files()


@router.get(
    "/files/{file_name}",
    response_model=SystemLogTailRead,
    summary="读取系统日志尾部内容",
    description="按文件名返回 server/logs 指定日志文件的最近若干行，仅管理员可用。",
    responses={
        status.HTTP_403_FORBIDDEN: {
            "model": ErrorResponse,
            "description": "只有管理员可以查看系统日志。",
        },
        status.HTTP_404_NOT_FOUND: {
            "model": ErrorResponse,
            "description": "日志文件不存在。",
        },
    },
)
def get_system_log_tail(
    file_name: str,
    _: Annotated[CurrentUserContext, Depends(require_platform_admin_user)],
    lines: Annotated[int, Query(ge=20, le=1000, description="返回的日志行数。")] = 300,
) -> SystemLogTailRead:
    try:
        return SystemLogService().read_tail(file_name, line_limit=lines)
    except FileNotFoundError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="日志文件不存在。",
        ) from exc
