"""GPU status polling via nvidia-smi."""

import subprocess
from dataclasses import dataclass
from typing import List


@dataclass
class GPUStatus:
    index: int
    name: str
    temp_c: int
    util_pct: int
    mem_used_mb: int
    mem_total_mb: int
    power_w: float

    @property
    def mem_pct(self) -> float:
        return 100.0 * self.mem_used_mb / max(self.mem_total_mb, 1)

    @property
    def short_name(self) -> str:
        return (self.name
                .replace("Tesla ", "")
                .replace("NVIDIA ", "")
                .replace("-PCIE-16GB", "")
                .replace("-PCIE-12GB", ""))


def poll_gpus() -> List[GPUStatus]:
    """Call nvidia-smi, return list of GPUStatus. Empty list on failure."""
    try:
        result = subprocess.run(
            ["nvidia-smi",
             "--query-gpu=index,name,temperature.gpu,utilization.gpu,"
             "memory.used,memory.total,power.draw",
             "--format=csv,noheader,nounits"],
            capture_output=True, text=True, timeout=5,
        )
        gpus = []
        for line in result.stdout.strip().split('\n'):
            parts = [p.strip() for p in line.split(',')]
            if len(parts) >= 7:
                gpus.append(GPUStatus(
                    index=int(parts[0]),
                    name=parts[1],
                    temp_c=int(parts[2]),
                    util_pct=int(parts[3]),
                    mem_used_mb=int(parts[4]),
                    mem_total_mb=int(parts[5]),
                    power_w=float(parts[6]),
                ))
        return gpus
    except Exception:
        return []
