#!/usr/bin/env python3
"""Boot installed Omarchy directly, log in on serial, and probe idle memory."""
import argparse
import json
import os
import re
import time

import pexpect

p = argparse.ArgumentParser()
p.add_argument("--settle", type=int, default=120)
p.add_argument("--ram", type=int, default=4096)
p.add_argument("--vga", default="std")
ARGS = p.parse_args()

HERE = os.path.dirname(os.path.abspath(__file__))
DISK = os.path.join(HERE, "omarchy-disk.qcow2")
KERNEL = os.path.join(HERE, "boot", "omarchy-vmlinuz")
INITRD = os.path.join(HERE, "boot", "omarchy-initramfs.img")
raw = open(os.path.join(HERE, "omarchy-cmdline.txt")).read().strip()
drop = ("quiet", "splash", "loglevel=0", "systemd.show_status=false",
        "rd.udev.log_level=0", "vt.global_cursor_default=0")
clean = " ".join(t for t in raw.split() if t not in drop)
clean += " console=ttyS0,115200 plymouth.enable=0 rd.plymouth=0 systemd.show_status=1"

qemu = [
    "qemu-system-x86_64", "-name", "omarchy-serial", "-m", str(ARGS.ram), "-smp", "4",
    "-machine", "pc", "-display", "none", "-vga", ARGS.vga, "-serial", "stdio", "-monitor", "none",
    "-kernel", KERNEL, "-initrd", INITRD, "-append", clean,
    "-drive", f"file={DISK},if=virtio,format=qcow2",
    "-netdev", "user,id=n1", "-device", "virtio-net-pci,netdev=n1",
]
result = {"qemu": " ".join(qemu), "cmdline": clean, "start": time.time()}
log = open(os.path.join(HERE, "omarchy-serial.serial"), "w", errors="replace")
child = pexpect.spawn(qemu[0], qemu[1:], timeout=900, logfile=log,
                      encoding="utf-8", codec_errors="replace")
child.delaybeforesend = 0.05
try:
    child.expect(r"login:\s*$", timeout=900)
    result["login_prompt_s"] = round(time.time() - result["start"], 1)
    child.sendline("omarchy")
    idx = child.expect([r"[Pp]assword:\s*", r"login:\s*$", pexpect.TIMEOUT], timeout=120)
    result["password_prompt"] = idx == 0
    if idx == 0:
        child.sendline("omarchy")
    # wait for an interactive shell
    child.sendline("id")
    ok = child.expect([r"uid=\d+\(omarchy\)", r"login:\s*$", pexpect.TIMEOUT], timeout=180)
    result["shell"] = ok == 0
    if ok != 0:
        raise RuntimeError("could not get a user shell")
    time.sleep(ARGS.settle)
    probe = r"""
echo '### IDENTITY'; whoami; hostname; uname -a
echo '### DESKTOP'; pgrep -a -f 'Hyprland|hyprland' | head -10 || true; pgrep -a -f 'quickshell' | head -10 || true
echo '### MEMINFO'; grep -E 'MemTotal|MemFree|MemAvailable|Buffers|Cached|SReclaimable|Shmem|SUnreclaim' /proc/meminfo
echo '### FREE'; free -m
echo '### TOP'; ps -eo pid,rss,comm --sort=-rss | head -25
echo '### COUNTS'; ps -eo comm | sort | uniq -c | sort -rn | head -20
echo '### PROBE_DONE'
"""
    child.sendline(probe.strip().replace("\n", "; "))
    child.expect(r"(?m)^### PROBE_DONE\s*$", timeout=180)
    result["probe_output"] = re.sub(r"\x1b\[[0-9;?]*[a-zA-Z]", "", child.before)[-20000:]
except Exception as e:
    result["error"] = repr(e)
finally:
    try:
        child.close(force=True)
    except Exception:
        pass
    result["duration_s"] = round(time.time() - result["start"], 1)

with open(os.path.join(HERE, "omarchy-serial.json"), "w") as f:
    json.dump(result, f, indent=2)
print(json.dumps({k: v for k, v in result.items() if "output" not in k}, indent=2))
if result.get("probe_output"):
    print("=== PROBE OUTPUT ===")
    print(result["probe_output"])
