"""Portable local PoC replay: standard-library Python only, no native Proof."""
import argparse
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import subprocess
import sys

HERE = Path(__file__).resolve().parent


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, required=True)
    args = parser.parse_args()
    args.output.mkdir(parents=True, exist_ok=False)
    commands = []
    for group, expected_exit, expected_matches in [('weak_helper', 1, 1),
            ('corrected_public', 0, 2), ('always_deny_control', 1, 1)]:
        argv = [sys.executable, '-B', str(HERE / 'run_behavior.py'), '--group', group]
        start = datetime.now(timezone.utc).isoformat()
        child = subprocess.run(argv, cwd=HERE, capture_output=True)
        (args.output / (group + '.stdout.json')).write_bytes(child.stdout)
        (args.output / (group + '.stderr.txt')).write_bytes(child.stderr)
        data = json.loads(child.stdout)
        accepted = (child.returncode == expected_exit and data['strong_passes'] == expected_matches
                    and data['selected_attempts'] == 2)
        commands.append({'group': group, 'argv': argv, 'cwd': str(HERE),
            'started_at_utc': start, 'finished_at_utc': datetime.now(timezone.utc).isoformat(),
            'exit_code': child.returncode, 'expected_exit_code': expected_exit,
            'strong_passes': data['strong_passes'], 'selected_attempts': data['selected_attempts'],
            'profiled_entries': data['profiled_entries'], 'profiled_returns': data['profiled_returns'],
            'stdout_sha256': hashlib.sha256(child.stdout).hexdigest(),
            'stderr_sha256': hashlib.sha256(child.stderr).hexdigest(),
            'expected_contrast_observed': accepted})
    result = {'schema': 'poc-quality-local-reproduction-v1', 'commands': commands,
        'accepted_demonstration': all(x['expected_contrast_observed'] for x in commands),
        'selected_attempts': sum(x['selected_attempts'] for x in commands),
        'profiled_entries': sum(x['profiled_entries'] for x in commands),
        'profiled_returns': sum(x['profiled_returns'] for x in commands),
        'native_proof_runs': 0,
        'interpretation': 'Expected failing weak/control children are not accepted as adequate; corrected public PoC passes the declared local-path/effect oracle and does not demonstrate an exploit.'}
    (args.output / 'commands.json').write_text(json.dumps(commands, indent=2) + '\n')
    (args.output / 'summary.json').write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps(result, indent=2))
    return 0 if result['accepted_demonstration'] else 1


if __name__ == '__main__':
    raise SystemExit(main())
