"""监控数据查询路由（读取 metrics.db）"""

from typing import Optional

from fastapi import APIRouter, Depends, Query
from sqlmodel import Session, select

from app.core.security import require_api_key
from app.database import get_metrics_session
from app.models.monitor import MetricPoint, ServerInfo
from app.services import cleanup_service, security_service

router = APIRouter(prefix="/api/monitor", tags=["monitor"])


@router.get("/security-overview", summary="所有服务器安全评分总览（风险高的在前）")
def security_overview(session: Session = Depends(get_metrics_session)):
    return security_service.get_security_overview(session)


@router.post(
    "/cleanup",
    summary="手动触发监控数据清理（按保留周期删除过期数据）",
    dependencies=[Depends(require_api_key)],
)
def cleanup(
    metrics_days: Optional[int] = Query(default=None, description="时序数据保留天数（默认取配置）"),
    security_days: Optional[int] = Query(default=None, description="安全检查保留天数（默认取配置）"),
    event_log_days: Optional[int] = Query(default=None, description="事件日志保留天数（默认取配置）"),
):
    return cleanup_service.cleanup_metrics(metrics_days, security_days, event_log_days)


@router.get("/{asset_id}/metrics", summary="资源监控时序（倒序，最新在前）")
def metrics(
    asset_id: int,
    limit: int = Query(default=50, ge=1, le=500),
    session: Session = Depends(get_metrics_session),
):
    stmt = (
        select(MetricPoint)
        .where(MetricPoint.asset_id == asset_id)
        .order_by(MetricPoint.ts.desc())
        .limit(limit)
    )
    return session.exec(stmt).all()


@router.get("/{asset_id}/info", summary="服务器信息快照")
def info(asset_id: int, session: Session = Depends(get_metrics_session)) -> Optional[ServerInfo]:
    return session.exec(
        select(ServerInfo).where(ServerInfo.asset_id == asset_id)
    ).first()


@router.get("/{asset_id}/security", summary="安全检查项（每项最新一条）")
def security(asset_id: int, session: Session = Depends(get_metrics_session)):
    return security_service.latest_checks(session, asset_id)


@router.get("/{asset_id}/security-score", summary="单个服务器安全评分与加固建议")
def security_score(asset_id: int, session: Session = Depends(get_metrics_session)):
    return security_service.get_asset_security(session, asset_id)
