"""Four bounded teaching gates; expected failing candidates are not accepted."""
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():
    if not __debug__:
        raise ValueError('Use normal Python, not -O')
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, required=True)
    args = parser.parse_args()
    output = args.output.resolve()
    if output.exists():
        raise SystemExit('Choose a new output directory; do not overwrite evidence')
    output.mkdir(parents=True)
    started = datetime.now(timezone.utc).isoformat()
    runs = []
    for variant, expected_exit in [('old', 0), ('candidate', 1), ('fixed', 0), ('reject_all', 1)]:
        before = datetime.now(timezone.utc).isoformat()
        command = [sys.executable, '-B', str(HERE / 'harness.py'), '--variant', variant]
        child = subprocess.run(command, cwd=HERE, capture_output=True, text=True)
        (output / (variant + '.stdout.json')).write_text(child.stdout)
        (output / (variant + '.stderr.txt')).write_text(child.stderr)
        if child.returncode != expected_exit or child.stderr:
            raise RuntimeError('Unexpected child outcome for ' + variant)
        result = json.loads(child.stdout)
        assert result['selected_cases'] == result['direct_handler_calls'] == 2
        assert result['whole_response_state_cases_passed'] == (2 if expected_exit == 0 else 1)
        assert all(r['entry_and_arguments_passed'] for r in result['observations'])
        if variant == 'candidate':
            assert result['status_only_cases_passed'] == 2 and not result['observations'][1]['typed_whole_rows_passed']
        if variant == 'reject_all':
            assert not result['observations'][0]['case_passed'] and result['observations'][1]['case_passed']
        runs.append({'variant': variant, 'started_at_utc': before, 'finished_at_utc': datetime.now(timezone.utc).isoformat(),
                     'command_portable': ['python3', '-B', 'harness.py', '--variant', variant],
                     'actual_interpreter': sys.executable, 'actual_exit_code': child.returncode,
                     'expected_exit_code': expected_exit, 'direct_handler_calls': result['direct_handler_calls'],
                     'whole_response_state_cases_passed': result['whole_response_state_cases_passed'],
                     'stdout_sha256': hashlib.sha256(child.stdout.encode()).hexdigest(),
                     'stderr_sha256': hashlib.sha256(child.stderr.encode()).hexdigest()})
    summary = {'schema': 'audit-closure-demonstration-v1', 'started_at_utc': started,
               'finished_at_utc': datetime.now(timezone.utc).isoformat(), 'runs': runs,
               'wrapper_passed': True, 'child_gates': 4, 'selected_cases': 2, 'variants': 4,
               'fresh_direct_handler_calls': 8, 'historical_migration_calls_not_in_fresh_denominator': 4,
               'historical_token_assertion_observations_not_replayed': 12,
               'meaning': 'Old and new teaching fix meet the two selected response/state expectations; faulty candidate and seeded reject-all repair are rejected. This is local instance evidence, not wider closure or an acceptance decision.'}
    (output / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n')
    print(json.dumps(summary, indent=2))


if __name__ == '__main__':
    main()
