"""Endpoint de health check del servidor."""
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session as DBSession
from sqlalchemy import text
from database import get_db
from models import Agent
from config import APP_VERSION
from datetime import datetime

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

# Se setea al arrancar el servidor
_start_time: datetime = None


def set_start_time():
    global _start_time
    _start_time = datetime.now()


@router.get("/health")
def health_check(db: DBSession = Depends(get_db)):
    """Health check completo: DB, agentes, uptime."""
    # DB
    db_ok = True
    try:
        db.execute(text("SELECT 1"))
    except Exception:
        db_ok = False

    # Agentes
    agents_total = db.query(Agent).count()
    agents_online = db.query(Agent).filter(Agent.status == "online").count()

    # Uptime
    uptime_seconds = 0
    if _start_time:
        uptime_seconds = int((datetime.now() - _start_time).total_seconds())

    # Status general
    status = "ok" if db_ok else "degraded"

    return {
        "status": status,
        "db": "ok" if db_ok else "error",
        "agents_total": agents_total,
        "agents_online": agents_online,
        "uptime_seconds": uptime_seconds,
        "version": APP_VERSION,
        "timestamp": datetime.now().isoformat(),
    }
