"""Agent 上报接收路由（数据写入 metrics.db）"""

from datetime import datetime

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

from app.core.security import require_agent_key
from app.database import get_metrics_session
from app.models.monitor import EventLog, MetricPoint, SecurityCheck, ServerInfo
from app.schemas.agent import AgentReport

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


@router.post(
    "/report",
    summary="Agent 上报资源/信息/安全状态",
    dependencies=[Depends(require_agent_key)],
)
def report(data: AgentReport, session: Session = Depends(get_metrics_session)) -> dict:
    # 资源监控时序
    if data.metrics:
        session.add(MetricPoint(asset_id=data.asset_id, **data.metrics.model_dump()))

    # 服务器信息快照（每资产一条，覆盖更新）
    if data.server_info:
        info = data.server_info.model_dump()
        info["last_seen"] = datetime.utcnow()
        existing = session.exec(
            select(ServerInfo).where(ServerInfo.asset_id == data.asset_id)
        ).first()
        if existing:
            for key, value in info.items():
                setattr(existing, key, value)
            session.add(existing)
        else:
            session.add(ServerInfo(asset_id=data.asset_id, **info))

    # 安全检查项
    if data.security:
        for check in data.security:
            session.add(SecurityCheck(asset_id=data.asset_id, **check.model_dump()))

    # 事件日志
    session.add(
        EventLog(
            level="info",
            source="agent",
            asset_id=data.asset_id,
            message=f"Agent 上报 asset_id={data.asset_id}",
        )
    )
    session.commit()
    return {"status": "ok", "asset_id": data.asset_id}
