"""PCKFQ5BB: Windows rig-only gates; never activates two-host roles."""
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
from datetime import datetime, timezone

ROOT = Path(r'C:\Users\decid\Documents\projects\spt-core')
TREE = ROOT / '.worktrees/hertz-S4-twohost-web'
TARGET = TREE / 'target'
OUT = Path(__file__).resolve().parent

def stamp():
    return datetime.now(timezone.utc).isoformat()

def save(name, payload):
    with (OUT / name).open('x', encoding='utf-8', newline='\n') as stream:
        json.dump(payload, stream, indent=2)

owner = json.loads((TARGET / 'POOL-OWNER.json').read_text())
assert Path(owner['owner_tree']).resolve() == TREE.resolve()
assert owner['lane_label'] == 'hertz-twohost-seed-docs-PCKFQ5BB'
env = dict(os.environ)
removed = []
for key in list(env):
    if key.upper().startswith(('OWL_', 'SPT_', 'NEXTEST_')) or key.upper() in {
        'CARGO_TARGET_DIR', 'CARGO_BUILD_JOBS', 'RUSTFLAGS', 'CARGO_ENCODED_RUSTFLAGS', 'CARGO_INCREMENTAL'
    }:
        removed.append(key)
        del env[key]
overlay = {
    'CARGO_TARGET_DIR': str(TARGET), 'CARGO_BUILD_JOBS': '2', 'NEXTEST_PROFILE': 'ci-windows',
    'SPT_TEST_EPHEMERAL_ADVISORY_PORTS': '1', 'SPT_ATTACH_IPC_DEADLINE_MS': '30000',
    'SPT_ATTACH_GATE_WATCHDOG_MS': '120000',
}
env.update(overlay)
assert 'SPT_TWO_HOST' not in env and 'SPT_TWO_HOST_ROLE' not in env
save('gate-environment.json', {'removed_names': removed, 'overlay': overlay})
cargo = shutil.which('cargo', path=env.get('PATH'))
trace = str(Path(env['LOCALAPPDATA']) / 'Programs/traceable-reqs/traceable-reqs.EXE')
assert cargo and Path(trace).is_file()
commands = [
    ('check', [cargo, 'check', '-p', 'spt-daemon', '--tests']),
    ('clippy', [cargo, 'clippy', '-p', 'spt-daemon', '--tests', '--', '-D', 'warnings']),
    ('inventory', [cargo, 'nextest', 'list', '-p', 'spt-daemon', '--test', 'twohost_web', '--profile', 'ci-windows', '--message-format', 'json']),
    ('twohost-web', [cargo, 'nextest', 'run', '-p', 'spt-daemon', '--test', 'twohost_web', '--profile', 'ci-windows', '--no-fail-fast', '--retries', '0', '--success-output', 'immediate', '--failure-output', 'immediate', '--color', 'never']),
    ('trace-version', [trace, '--version']),
    ('trace-check', [trace, 'check']),
]
results = []
for name, command in commands:
    before = shutil.disk_usage(TARGET).free
    assert before > 32 * 1024 ** 3, 'capacity floor: refusing next producer'
    started = stamp()
    print(json.dumps({'stage': name, 'state': 'START', 'at': started, 'free_bytes': before}), flush=True)
    with (OUT / (name + '.stdout')).open('xb') as stdout, (OUT / (name + '.stderr')).open('xb') as stderr:
        process = subprocess.run(command, cwd=TREE, env=env, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr)
    row = {'stage': name, 'command': command, 'started': started, 'ended': stamp(), 'native_exit': process.returncode,
           'free_before': before, 'free_after': shutil.disk_usage(TARGET).free}
    save(name + '-exit.json', row)
    results.append(row)
    print(json.dumps(row), flush=True)
    if process.returncode != 0:
        save('gates-result.json', {'status': 'STOPPED_ON_RED', 'results': results})
        sys.exit(process.returncode)
    if name == 'trace-version':
        assert '0.4.1' in (OUT / 'trace-version.stdout').read_text(encoding='utf-8-sig'), 'traceable version mismatch'
save('gates-result.json', {'status': 'GATES_COMPLETE', 'results': results,
     'twohost_body_evidence': 'NONE: every existing twohost_web cell is SPT_TWO_HOST/role-gated. This run proves only the unopted-in paths. S5 golden owns the true twohost bodies.'})
