#!/usr/bin/env python3
"""Print one JSON line of host stats: memory (vm_stat), load, CPU, RSS by engine."""
import json, subprocess, re, sys, time
def vmstat():
    o = subprocess.run(["vm_stat"], capture_output=True, text=True).stdout
    ps = int(re.search(r"page size of (\d+)", o).group(1))
    g = lambda k: int(re.search(k + r":\s+(\d+)", o).group(1)) * ps / 2**20
    return {"free_mb": g("Pages free"), "active_mb": g("Pages active"), "inactive_mb": g("Pages inactive"),
            "wired_mb": g("Pages wired down"), "compressed_mb": g("Pages occupied by compressor"),
            "used_mb": g("Pages active") + g("Pages wired down") + g("Pages occupied by compressor")}
def cpu():
    o = subprocess.run(["top", "-l", "2", "-n", "0", "-s", "1"], capture_output=True, text=True).stdout
    m = re.findall(r"CPU usage: ([\d.]+)% user, ([\d.]+)% sys, ([\d.]+)% idle", o)[-1]
    return {"cpu_user": float(m[0]), "cpu_sys": float(m[1]), "cpu_idle": float(m[2])}
def rss():
    o = subprocess.run(["ps", "-axo", "rss=,command="], capture_output=True, text=True).stdout
    groups = {"qemu": "qemu-system", "vz_xpc": "com.apple.Virtualization.VirtualMachine",
              "container_runtime": "container-runtime-linux", "limactl": "limactl", "cua": "Cua Spaces.app/Contents/MacOS/cua"}
    out = {k: 0.0 for k in groups}; cnt = {k: 0 for k in groups}
    for line in o.splitlines():
        line = line.strip()
        if not line: continue
        r, c = line.split(None, 1)
        for k, p in groups.items():
            if p in c: out[k] += int(r) / 1024; cnt[k] += 1
    return {"rss_mb": out, "procs": cnt}
d = {"t": time.time(), "label": sys.argv[1] if len(sys.argv) > 1 else ""}
d.update(vmstat()); d.update(cpu()); d.update(rss())
d["load1"] = float(subprocess.run(["sysctl", "-n", "vm.loadavg"], capture_output=True, text=True).stdout.split()[1])
print(json.dumps(d))
