"""Authorized #307 sync rider proof; reuse the retained native/disk/process guard."""
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('sync_guard307', SOURCE)
g = importlib.util.module_from_spec(spec)
spec.loader.exec_module(g)
g.OUT = OUT
g.TREE = ROOT / '.worktrees/hertz-307-sync-wall-bound'
g.TARGET = g.TREE / 'target'
g.psutil = None  # Existing bounded CIM backend; direct psutil census previously hung.
g.PHASES = ('pool-claim', 'proof', 'checks', 'pool-release')
HELPER = ROOT / '.spt/preserved/302/todlando-step3-field/pool-controller.exe'
HELPER_SHA = '2ec9a1f93ce4d52454c49a5c01593e6a292ca75286dc5798d26a0ed6858e01bf'
SCOPE = ['--locked', '-p', 'spt-daemon', '--test', 'sync']
TESTS = (
    'concurrent_writes_reconcile_on_elected_node_and_converge',
    'two_tier_sync_lands_and_gate_refuses_server_side',
    'torn_pull_recovers_by_repulling',
)
EXPRESSION = ' | '.join('test(=' + name + ')' for name in TESTS)


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


class Phase(g.Phase):
    def prepare(self):
        super().prepare()
        for key in ('SPT_ATTACH_IPC_DEADLINE_MS', 'SPT_ATTACH_GATE_WATCHDOG_MS'):
            self.env.pop(key, None)
            self.receipt['environment_allowlist'].pop(key, None)
        self.env['CARGO_INCREMENTAL'] = '0'
        self.receipt['environment_allowlist']['CARGO_INCREMENTAL'] = '0'
        self.receipt.update(authority='Doyle AGYCCVIE; proof shape LN4AMGIE',
                            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')
        result = g.subprocess.run(
            ['gh', 'run', 'list', '--repo', 'BigscreenVR/spt-bs-core', '--limit', '50',
             '--json', 'databaseId,status,workflowName'],
            env=self.env, capture_output=True, timeout=30, check=True)
        runs = json.loads(result.stdout)
        g.save(self.dir / 'workflow-admission.json', runs)
        self.receipt['nonterminal_workflows'] = [r for r in runs if r['status'] != 'completed']
        self.flush()
        if self.receipt['nonterminal_workflows']:
            raise RuntimeError('nonterminal workflow admission refused')

    def execute(self):
        if self.name == 'pool-claim':
            self.run('claim', [str(HELPER), 'pool-claim', '--pool', str(g.TARGET),
                              '--label', 'hertz-307-sync-wall-bound', '--holder-pid', str(g.os.getpid())],
                     timeout=120)
        elif self.name == 'proof':
            selected = self.inventory('inventory', SCOPE, EXPRESSION)
            if selected != {('spt-daemon', 'sync', name) for name in TESTS}:
                raise RuntimeError('expected exactly the sync pair plus torn_pull')
            for index in range(1, 4):
                self.run('tests-' + str(index),
                         ['cargo', 'nextest', 'run', *SCOPE, '--profile', 'ci-windows',
                          '--test-threads', '1', '--retries', '0',
                          '--success-output', 'immediate', '-E', EXPRESSION], timeout=900)
        elif self.name == 'checks':
            self.run('clippy', ['cargo', 'clippy', *SCOPE, '--', '-D', 'warnings'])
            self.run('trace', ['traceable-reqs', 'check', '--json'], timeout=600)
            self.run('format', ['rustfmt', '--check', '--edition', '2021',
                               'crates/spt-daemon/tests/sync.rs'], timeout=60)
        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())
