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

from typing import Optional

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

from app.database import get_metrics_session
from app.models.monitor import MetricPoint, SecurityCheck, ServerInfo

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


@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)):
    stmt = (
        select(SecurityCheck)
        .where(SecurityCheck.asset_id == asset_id)
        .order_by(SecurityCheck.ts.desc())
        .limit(50)
    )
    checks = session.exec(stmt).all()
    latest_by_item = {}
    for check in checks:
        if check.check_item not in latest_by_item:
            latest_by_item[check.check_item] = check
    return list(latest_by_item.values())
