#!/usr/bin/env python3
import glob, os, shutil, subprocess

print("=== ALFRED GPU & VRAM TELEMETRY PROBE ===")
if shutil.which("nvidia-smi"):
    r = subprocess.run(["nvidia-smi", "--query-gpu=name,temperature.gpu,utilization.gpu,memory.used,memory.total", "--format=csv,noheader"], capture_output=True, text=True, timeout=4)
    if r.returncode == 0 and r.stdout.strip():
        print("NVIDIA GPU: " + r.stdout.strip())

pci_lines = []
try:
    r_pci = subprocess.run(["lspci"], capture_output=True, text=True, timeout=4)
    pci_lines = [ln.strip() for ln in r_pci.stdout.splitlines() if any(k in ln for k in ("VGA", "3D controller", "Display controller"))]
except Exception:
    pass

amd_name = "AMD Radeon GPU"
for pl in pci_lines:
    if any(k in pl for k in ("AMD", "ATI", "Radeon")):
        raw_n = pl.split(":", 2)[-1].strip()
        amd_name = "AMD Radeon Barcelo" if "Barcelo" in raw_n else raw_n[:64]
        break

for cd in sorted(glob.glob("/sys/class/drm/card*/device")):
    if os.path.isfile(cd + "/vendor") and open(cd + "/vendor").read().strip().lower() == "0x1002":
        vt = int(open(cd + "/mem_info_vram_total").read().strip()) // 1048576 if os.path.isfile(cd + "/mem_info_vram_total") else 0
        vu = int(open(cd + "/mem_info_vram_used").read().strip()) // 1048576 if os.path.isfile(cd + "/mem_info_vram_used") else 0
        gt = int(open(cd + "/mem_info_gtt_total").read().strip()) // 1048576 if os.path.isfile(cd + "/mem_info_gtt_total") else 0
        gu = int(open(cd + "/mem_info_gtt_used").read().strip()) // 1048576 if os.path.isfile(cd + "/mem_info_gtt_used") else 0
        util = open(cd + "/gpu_busy_percent").read().strip() if os.path.isfile(cd + "/gpu_busy_percent") else "0"
        t_c = 0
        for tf in glob.glob(cd + "/hwmon/hwmon*/temp1_input"):
            t_c = int(open(tf).read().strip()) // 1000
            break
        print(f"AMD GPU: {amd_name}, {t_c} C, {util}%, {vu+gu} MiB / {vt+gt} MiB")

for line in pci_lines:
    print("PCI Adapter: " + line)
