#!/usr/bin/env python3
import os
import sys
import time

CODE = os.path.expanduser("~/code")
HOME = os.path.expanduser("~")
INTERVAL = float(os.environ.get("INTERVAL", "2"))
PLUMBING = ("--bg-pty-host", "--bg-spare", "--json-path", "--spawned-by")


def processes():
	found = {}
	for pid in os.listdir("/proc"):
		if not pid.isdigit():
			continue
		try:
			argv = open(f"/proc/{pid}/cmdline", "rb").read().decode("utf-8", "replace").split("\0")[:-1]
			cwd = os.readlink(f"/proc/{pid}/cwd")
			ppid = next(int(line.split()[1]) for line in open(f"/proc/{pid}/status") if line.startswith("PPid:"))
		except (OSError, StopIteration, ValueError):
			continue
		if argv:
			found[int(pid)] = (argv, ppid, cwd.removesuffix(" (deleted)"))
	return found


def shown(cwd):
	if cwd == CODE:
		return "code"
	if cwd.startswith(f"{CODE}/"):
		return os.path.relpath(cwd, CODE)
	return cwd.replace(HOME, "~", 1)


def rows(found):
	wrappers = set()
	for pid, (argv, ppid, _) in found.items():
		if not os.path.basename(argv[0]).startswith("claude") or any(flag in argv for flag in PLUMBING):
			continue
		parent = found.get(ppid)
		if parent and os.path.basename(parent[0][0]).startswith("python"):
			wrappers.add(ppid)
	listed, claimed = [], set()
	for pid in wrappers:
		status = "Auto"
		for child, (argv, ppid, _) in found.items():
			if ppid == pid and os.path.basename(argv[0]).startswith("claude"):
				claimed.add(child)
				if "--resume" in argv:
					status = "Inter"
		listed.append((status, shown(found[pid][2])))
	for pid, (argv, _, cwd) in found.items():
		if pid in claimed or pid in wrappers:
			continue
		if not os.path.basename(argv[0]).startswith("claude"):
			continue
		if any(flag in argv for flag in PLUMBING):
			continue
		listed.append(("Other", shown(cwd)))
	return sorted(listed, key=lambda row: (row[1], row[0]))


try:
	while True:
		listed = rows(processes())
		width = max([len(path) for _, path in listed] + [4])
		out = [f"{'STATUS':<6}  {'PATH':<{width}}", f"{'-' * 6}  {'-' * width}"]
		out += [f"{status:<6}  {path:<{width}}" for status, path in listed] or ["(none running)"]
		sys.stdout.write("\x1b[H\x1b[2J" + "\n".join(out) + "\n")
		sys.stdout.flush()
		time.sleep(INTERVAL)
except KeyboardInterrupt:
	pass
