from pathlib import Path
import subprocess
import time

pid = 591161
root = Path("/srv/home/gc-sdk/ipu-stack")
output = root / "artifacts/vit/optimized-so400m-fp8"
stat = Path(f"/proc/{pid}/stat")
started = stat.read_text().split()[21] if stat.exists() else None
while started is not None:
    try:
        fields = stat.read_text().split()
        if fields[21] != started or fields[2] == "Z":
            break
    except FileNotFoundError:
        break
    time.sleep(5)
profile = output / "profile.ipuprof"
if profile.exists():
    cli = str(root / "target/release/ipu-stack")
    subprocess.run([cli, "profile-render", str(profile), "-o", str(output / "profile.html")], check=True)
    for kind in ["kernel", "operation"]:
        with (output / f"{kind}-summary.json").open("w") as summary:
            subprocess.run([cli, "profile-query", str(profile), "--kind", "compute", "--group-by", kind, "--limit", "100", "--json"], stdout=summary, check=True)
else:
    print("No profile was produced; inspect run.log for the build or hardware error.")
