"""System and health endpoints."""

import os

from fastapi import APIRouter, Depends, Query

from peon_mcp.common.dependencies import get_db
from peon_mcp.db import get_db_path, row_to_dict
from peon_mcp.system.schemas import LoopsResponse, SystemInfoResponse

router = APIRouter(tags=["System"])


@router.get("/api/health")
async def health_check():
    """Health check endpoint. Returns auth_required status."""
    return {
        "status": "ok",
        "auth_required": bool(os.environ.get("PEON_API_KEY")),
    }


@router.get("/api/system-info", response_model=SystemInfoResponse)
async def system_info():
    try:
        import importlib.metadata
        version = importlib.metadata.version("peon-mcp")
    except Exception:
        version = "dev"

    return {
        "db_path": get_db_path(),
        "version": version,
    }


@router.get("/api/loops", response_model=LoopsResponse)
async def list_loops(
    project_id: str | None = Query(default=None),
    db=Depends(get_db),
):
    query = (
        "SELECT * FROM loop_heartbeats"
        " WHERE last_heartbeat >= datetime('now', '-90 seconds')"
    )
    params: list = []
    if project_id:
        query += " AND project_id = ?"
        params.append(project_id)
    query += " ORDER BY started_at DESC"
    rows = await db.execute_fetchall(query, params)
    loops = [row_to_dict(r) for r in rows]
    return {
        "active_count": len(loops),
        "loops": loops,
    }
