"""STEP3 one-shot remedy proofs; reuses the established quiet, disk and source guards."""
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]
BASE = OUT.parent / 'todlando-step2/run.py'
spec = importlib.util.spec_from_file_location('step3_remedy_base', BASE)
r = importlib.util.module_from_spec(spec)
spec.loader.exec_module(r)
g = r.g
r.OUT = g.OUT = OUT
g.TREE = ROOT / '.worktrees/302-meet-offload'
g.TARGET = g.TREE / 'target'
MAPPER = 'net::endpoint::tests::all_bind_scopes_exchange_without_portmapper_activity'

class Step3Phase(r.Phase):
    def prepare(self):
        super().prepare()
        self.receipt['step3_driver_sha256'] = g.digest(Path(__file__))
        self.receipt['authority'] = ['MTWAADNS', 'OLFFLWCR', 'YMD36GJF']
        self.flush()

    def execute(self):
        if self.name == 'pool-claim':
            helper = g.TARGET / 'debug/xtask.exe'
            self.receipt['prebuilt_xtask_sha256'] = g.digest(helper)
            self.run('claim', [str(helper), 'pool-claim', '--pool', 'target', '--label', 'todlando-302-step3'], timeout=120)
        elif self.name in ('mapper-red', 'mapper-green'):
            scope = ['--locked', '-p', 'spt-net', '--lib']
            expression = 'test(=' + MAPPER + ')'
            selected = self.inventory('inventory', scope, expression)
            if selected != {('spt-net', 'spt_net', MAPPER)}:
                raise RuntimeError('exact mapper regression inventory required: ' + repr(selected))
            expected = 100 if self.name == 'mapper-red' else 0
            stdout, stderr = self.run('tests', ['cargo', 'nextest', 'run', *scope,
                '--profile', 'ci-windows', '--test-threads', '2', '--retries', '0',
                '--no-fail-fast', '--success-output', 'immediate', '-E', expression], expected=expected)
            if expected and 'All: endpoint activated the portmapper' not in (stdout.read_text(errors='replace') + stderr.read_text(errors='replace')):
                raise RuntimeError('red did not fail on the intended ordinary-node mapper activity assertion')
        elif self.name == 'fixtures':
            self.run('fixture-build', ['cargo', 'build', '--locked', '-p', 'mock-adapter', '--bin', 'mock-session'])
            fixture = g.TARGET / 'debug/mock-session.exe'
            self.receipt['fixture'] = dict(path=str(fixture), sha256=g.digest(fixture), bytes=fixture.stat().st_size)
            self.flush()
        else:
            super().execute()

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