"""GPU state API endpoints."""

from __future__ import annotations

from fastapi import APIRouter, HTTPException

from radix_edge.db import get_db
from radix_edge.models import GPU

router = APIRouter(prefix="/v1/gpus", tags=["gpus"])


@router.get("")
async def list_gpus():
    """List all detected GPUs with live state."""
    with get_db() as db:
        rows = db.execute("SELECT * FROM gpus ORDER BY gpu_index").fetchall()
        return {"gpus": [GPU.from_row(r).to_dict() for r in rows]}


@router.get("/{gpu_index}")
async def get_gpu(gpu_index: int):
    """Get a single GPU's state."""
    with get_db() as db:
        row = db.execute("SELECT * FROM gpus WHERE gpu_index = ?", (gpu_index,)).fetchone()
        if not row:
            raise HTTPException(status_code=404, detail=f"GPU {gpu_index} not found")
        return GPU.from_row(row).to_dict()
