"""Portable standard-library replay; expected failing children are not acceptance."""
from pathlib import Path
import argparse,datetime,hashlib,json,subprocess,sys,platform
BASE=Path(__file__).resolve().parent

def main():
    p=argparse.ArgumentParser();p.add_argument('--output',required=True);a=p.parse_args();out=Path(a.output).resolve();out.mkdir(parents=True,exist_ok=False)
    before={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in [BASE/'implementation.py',BASE/'run.py',BASE/'expected.json',BASE/'CONTRACT.md',BASE/'hazard-record.json',BASE/'reproduce.py']};commands=[];reports={}
    for variant in ['baseline','corrected','reject-all']:
        argv=[sys.executable,'-B',str(BASE/'run.py'),'--variant',variant];start=datetime.datetime.now(datetime.timezone.utc).isoformat();c=subprocess.run(argv,cwd=BASE,capture_output=True,timeout=30)
        (out/(variant+'.stdout.json')).write_bytes(c.stdout);(out/(variant+'.stderr.txt')).write_bytes(c.stderr)
        commands.append({'variant':variant,'argv':argv,'cwd':str(BASE),'startedAtUtc':start,'finishedAtUtc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'exitCode':c.returncode,'stdoutSha256':hashlib.sha256(c.stdout).hexdigest(),'stderrSha256':hashlib.sha256(c.stderr).hexdigest()});(out/'commands.json').write_text(json.dumps(commands,indent=2)+'\n')
        expected_exit=0 if variant=='corrected' else 1
        assert c.returncode==expected_exit,(variant,'Unexpected child exit',c.returncode)
        j=json.loads(c.stdout);assert j['traceEntryGate'];assert j['strongContractGate'] is (variant=='corrected');assert j['weakerResourceOnlyGate'] is (variant!='baseline');reports[variant]=j
    after={name:hashlib.sha256((BASE/name).read_bytes()).hexdigest() for name in before};assert before==after
    totals={k:sum(r['actualSelectedMethodEntryCounts'][k] for r in reports.values()) for k in ['__init__','join','publish','drain']}
    summary={'completedAtUtc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'runtime':sys.version,'platform':platform.platform(),'commands':commands,'sourceAndInputsSha256':before,'sourceAndInputsUnchanged':True,'variants':{v:{'strongContractGate':j['strongContractGate'],'weakerResourceOnlyGate':j['weakerResourceOnlyGate'],'matchingSnapshots':j['matchingSnapshots'],'snapshotCount':j['snapshotCount'],'actualSelectedMethodEntryCounts':j['actualSelectedMethodEntryCounts'],'maxPerConsumer':j['maxPerConsumer'],'maximumTotalQueuedLogicalPayloadBytesAcrossTwoCurrentQueues':j['maximumTotalQueuedLogicalPayloadBytesAcrossTwoCurrentQueues'],'finalDelivered':j['finalDelivered']} for v,j in reports.items()},'totals':{'freshInstances':3,'selectedSchedulesPerVariant':1,'publicationsPerVariant':7,'recordedPublishEntries':totals['publish'],'recordedDrainEntries':totals['drain'],'initialJoinEntries':6,'explicitRejoinEntries':3,'recordedJoinEntries':totals['join'],'recordedCoreConstructorEntries':totals['__init__'],'selectedMethodEntries':sum(totals.values()),'stateObservations':sum(j['snapshotCount'] for j in reports.values())},'wrapperExitMeaning':'Expected baseline/control failures and corrected selected-contract acceptance reproduced. This wrapper does not accept the faulty variants, measure RSS/throughput, close other obligations, accept residual risk or approve release.','noNetworkOrExternalDependencies':True,'noRiskAcceptance':True}
    (out/'summary.json').write_text(json.dumps(summary,indent=2)+'\n');print(json.dumps(summary));return 0
if __name__=='__main__':raise SystemExit(main())
