"""Autostart census (doyle HDDEXZNE + YITQXO5A): per spt integration binary, the
CLI verb paths it passes to the spt exe, HEAVY membership, the current xtask
detector verdict, isolated-home use, and daemon-stop / inhibit presence.
Scope mirrors xtask check_heavy_integration_classification: top-level
crates/spt/tests/*.rs only; helper-module use is reported separately.
Run from the repo root. Writes rows.json next to this file."""
import json, os, re, sys

ROOT = os.getcwd()
T = os.path.join(ROOT, 'crates', 'spt', 'tests')
OUT = os.path.dirname(os.path.abspath(__file__))

golden = open(os.path.join(ROOT, '.github', 'workflows', 'golden.yml'), encoding='utf-8').read()
m = re.search(r"package\(spt\) & kind\(test\) & binary\(/\^\(([^)]*)\)", golden)
heavy = set(m.group(1).split('|')) if m else set()


def detector(src):  # verbatim port of xtask spawns_daemon_tree
    flat = ' '.join(src.split())
    return ('"daemon", "run"' in flat or '"daemon", "brain"' in flat
            or 'supervise_brain(' in flat)


LIT = r'"([a-z][a-z0-9-]*)"'
# a string-literal array or args([...]) whose first 1-2 elements are verb-like
ARR = re.compile(r'\[\s*' + LIT + r'(?:\s*,\s*' + LIT + r')?')
ARG_CHAIN = re.compile(r'\.arg\(\s*' + LIT + r'\s*\)(?:\s*\.arg\(\s*' + LIT + r'\s*\))?')

rows = []
for f in sorted(os.listdir(T)):
    if not f.endswith('.rs'):
        continue
    name = f[:-3]
    src = open(os.path.join(T, f), encoding='utf-8').read()
    flat = ' '.join(src.split())
    paths = set()
    for rx in (ARR, ARG_CHAIN):
        for a, b in rx.findall(flat):
            paths.add(a if not b else f'{a} {b}')
            paths.add(a)
    rows.append({
        'bin': name,
        'runs_spt_exe': 'CARGO_BIN_EXE_spt' in src,
        'isolated_home': ('"SPT_HOME"' in src) or ('TestHome' in src),
        'heavy': name in heavy,
        'detector': detector(src),
        'daemon_stop': bool(re.search(r'"(daemon|node)",\s*"stop"', flat)),
        'inhibit': ('daemon-stop.inhibit' in src) or ('STOP_INHIBIT' in src) or ('stop_inhibit' in src),
        'uses_create_endpoint': 'create_endpoint(' in src,
        'mods': sorted(set(re.findall(r'^\s*mod\s+(\w+)\s*;', src, re.M))),
        'paths': sorted(paths),
    })
json.dump(rows, open(os.path.join(OUT, 'rows.json'), 'w'), indent=1)
print(len(rows), 'binaries;', sum(r['heavy'] for r in rows), 'heavy;',
      sum(r['detector'] for r in rows), 'detector-true;', len(heavy), 'names in golden spt heavy list')
