#!/usr/bin/env python3
"""One JSON line: load avg, memory, other VMs/daemons running on this host (not ours)."""
import json, os, re, subprocess, sys, time
ps = subprocess.run(["ps", "-axo", "pid,%cpu,rss,command"], capture_output=True, text=True).stdout.splitlines()[1:]
home = os.environ.get("CUA_HOME", "/nonexistent")
other, ours = [], 0
for l in ps:
    pid, cpu, rss, cmd = l.split(None, 3)
    vm = re.search(r"qemu-system|Virtualization\.VirtualMachine|limactl hostagent|cua-vz|container-runtime-linux", cmd)
    if not vm:
        continue
    if home in cmd:
        ours += 1
        continue
    name = re.search(r"-name (\S+)", cmd)
    other.append({"pid": int(pid), "cpu": float(cpu), "rss_mb": int(rss) // 1024,
                  "what": (name.group(1) if name else cmd.split()[0].rsplit("/", 1)[-1])[:60]})
vs = subprocess.run(["vm_stat"], capture_output=True, text=True).stdout
pg = int(re.search(r"page size of (\d+)", vs).group(1))
g = lambda k: int(re.search(k + r":\s+(\d+)", vs).group(1)) * pg // 1048576
print(json.dumps({"at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "label": sys.argv[1] if len(sys.argv) > 1 else "",
    "load_avg": [round(x, 2) for x in os.getloadavg()], "free_mb": g("Pages free"), "inactive_mb": g("Pages inactive"),
    "compressed_mb": g("Pages occupied by compressor"), "other_vms": len(other), "other_vm_procs": other, "our_vm_procs": ours}))
