"""#307 test-only lane: reuse the retained native/process/disk guard unchanged."""
import importlib.util
import json
from pathlib import Path
import sys

sys.dont_write_bytecode = True
OUT = Path(__file__).resolve().parent
ROOT = OUT.parents[3]
SOURCE = ROOT / '.spt/preserved/308-registry-process-lock/windows-validation/run.py'
spec = importlib.util.spec_from_file_location('guard307', SOURCE)
g = importlib.util.module_from_spec(spec)
spec.loader.exec_module(g)
g.OUT = OUT
g.TREE = ROOT / '.worktrees/hertz-307-ack-jitter'
g.TARGET = g.TREE / 'target'
# Use the guard's existing bounded CIM backend. Direct psutil cmdline/cwd census
# blocked inside Windows APIs and killed the parent Eval kernel; do not retry it.
g.psutil = None
HELPER = ROOT / '.spt/preserved/302/todlando-step3-field/pool-controller.exe'
HELPER_SHA = '2ec9a1f93ce4d52454c49a5c01593e6a292ca75286dc5798d26a0ed6858e01bf'
LIVE = 'refresh_resumes_bounded_input_ack_without_replacement_poison'
POLICY = 'refresh_ack_policy_distinguishes_jitter_from_stalls'
SCOPE = ['--locked', '-p', 'spt-daemon', '--test', 'refresh_freeze']


def quiet_gate(rows):
    busy = [row for row in rows if row['builder'] or row['own_target']
            or (row['name'] or '').lower() == 'runner.worker.exe']
    if busy:
        raise RuntimeError('builder/runner/pool user refused: ' + repr([(r['pid'], r['name']) for r in busy]))


g.gate = quiet_gate
g.PHASES = ('pool-claim', 'build', 'live', 'checks', 'pool-release')


class Phase(g.Phase):
    def prepare(self):
        super().prepare()
        for name in ('SPT_ATTACH_IPC_DEADLINE_MS', 'SPT_ATTACH_GATE_WATCHDOG_MS'):
            self.env.pop(name, None)
            self.receipt['environment_allowlist'].pop(name, None)
        self.receipt.update(authority='Doyle RIZ6GS7C; local window F5LEIIHF',
                            inherited_guard_sha256=g.digest(SOURCE), lane_driver_sha256=g.digest(Path(__file__)),
                            pool_controller_sha256=g.digest(HELPER))
        if g.digest(HELPER) != HELPER_SHA:
            raise RuntimeError('pool controller hash mismatch')
        self.flush()

    def execute(self):
        if self.name == 'pool-claim':
            self.run('claim', [str(HELPER), 'pool-claim', '--pool', str(g.TARGET),
                              '--label', 'hertz-307-ack-jitter', '--holder-pid', str(g.os.getpid())], timeout=120)
        elif self.name == 'build':
            self.run('build', ['cargo', 'build', '--locked', '-p', 'spt', '--bin', 'spt'])
            self.receipt['candidate_sha256'] = g.digest(g.TARGET / 'debug/spt.exe')
            self.flush()
        elif self.name == 'live':
            candidate = g.TARGET / 'debug/spt.exe'
            overlay = dict(SPT_REFRESH_RIG_SPT=str(candidate), SPT_REFRESH_RIG_EXPECTED_SHA256=g.digest(candidate),
                           SPT_REFRESH_RIG_PYTHON=r'C:\Program Files\Python312\python.exe',
                           SPT_REFRESH_RIG_OUTPUT=str(OUT / 'live-rig'))
            if not Path(overlay['SPT_REFRESH_RIG_PYTHON']).is_file():
                raise RuntimeError('required explicit Python312 executable absent')
            self.env.update(overlay)
            self.receipt['environment_allowlist'].update(overlay)
            expression = 'test(=' + LIVE + ') | test(=' + POLICY + ')'
            selected = self.inventory('inventory', SCOPE, expression)
            if selected != {('spt-daemon', 'refresh_freeze', name) for name in (LIVE, POLICY)}:
                raise RuntimeError('expected one live cell plus deterministic policy wrapper')
            self.run('tests', ['cargo', 'nextest', 'run', *SCOPE, '--profile', 'ci-windows',
                              '--test-threads', '1', '--retries', '0', '--no-capture', '-E', expression], timeout=600)
            observed = json.loads((OUT / 'live-rig/observation/receipt.json').read_bytes())
            native = json.loads((OUT / 'live-rig/native.json').read_bytes())
            if (observed['status'] != 'PASS' or not observed['cleanup']['pass']
                    or native['termination'] != 'CONFIRMED_GONE' or native['job']['active_processes'] != 0):
                raise RuntimeError('live verdict or teardown not proven')
            self.receipt['live_receipt_sha256'] = g.digest(OUT / 'live-rig/observation/receipt.json')
            self.flush()
        elif self.name == 'checks':
            self.run('clippy', ['cargo', 'clippy', *SCOPE, '--', '-D', 'warnings'])
            self.run('trace', ['traceable-reqs', 'check', '--json'], timeout=600)
        elif self.name == 'pool-release':
            self.run('release', [str(HELPER), 'pool-release', '--pool', str(g.TARGET)], timeout=120)
        else:
            raise RuntimeError('unknown phase')


g.Phase = Phase
if __name__ == '__main__':
    sys.exit(g.main())
