"""Six-call teaching campaign is orchestrated by reproduce.py."""
import argparse
from datetime import datetime, timezone
import hashlib
import importlib
import inspect
import json
from pathlib import Path
import platform
import sys
import tempfile

import strong_witness
import weak_witness

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


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--variant', choices=['baseline', 'corrected', 'always_cancel'], required=True)
    args = parser.parse_args()
    function = importlib.import_module(args.variant).render
    source = HERE / (args.variant + '.py')
    identity = {'file': source.name, 'sha256': hashlib.sha256(source.read_bytes()).hexdigest(),
                'function': function.__module__ + '.' + function.__qualname__,
                'function_source_sha256': hashlib.sha256(inspect.getsource(function).encode()).hexdigest(),
                'first_line': function.__code__.co_firstlineno,
                'matching_rule': 'frame.f_code is exact imported variant.render.__code__'}
    cases = json.loads((HERE / 'cases.json').read_text())
    entries, returns, results = [], [], []
    phase = None

    def profile(frame, event, arg):
        if frame.f_code is function.__code__:
            if event == 'call':
                entries.append({'case': phase, 'chunks_hex': [x.hex() for x in frame.f_locals['chunks']],
                                'cancel_after': frame.f_locals['cancel_after'],
                                'destination_name': frame.f_locals['destination'].name})
            elif event == 'return':
                returns.append({'case': phase, 'reply': arg})

    previous = sys.getprofile()
    if previous is not None:
        raise RuntimeError('Use an unprofiled interpreter')
    try:
        sys.setprofile(profile)
        for case in cases:
            phase = case['id']
            with tempfile.TemporaryDirectory(prefix='documented-claim-case-') as directory:
                target = Path(directory) / 'target.bin'
                unrelated = Path(directory) / 'unrelated.bin'
                target.write_bytes(b'KEEP')
                unrelated.write_bytes(b'OTHER')
                before = {p.name: p.read_bytes().hex() for p in [target, unrelated]}
                if before != {'target.bin': '4b454550', 'unrelated.bin': '4f54484552'}:
                    raise RuntimeError('Literal starting condition not established')
                reply = function([b'A', b'B'], case['cancel_after'], target)
                actual = {'reply': reply, 'files': {p.name: p.read_bytes().hex() for p in [target, unrelated]}}
                witness = (strong_witness.TestNoPartialOutput if case['id'] == 'cancel_after_first'
                           else strong_witness.TestNormalCompletion)
                strong = witness(actual)
                literal = strong_witness.exact_equal(actual, case['expected'])
                if strong != literal:
                    raise RuntimeError('Witness and independent fixed case table disagree')
                weak = weak_witness.TestNoPartialOutput(actual) if case['id'] == 'cancel_after_first' else None
                results.append({'id': phase, 'cancel_after': case['cancel_after'], 'before_files': before,
                                'actual': actual, 'expected': case['expected'], 'strong_case_passed': strong,
                                'weak_cancel_status_passed': weak})
    finally:
        sys.setprofile(previous)
    if len(entries) != 2 or len(returns) != 2:
        raise RuntimeError('Exact render call observations incomplete')
    result = {'schema': 'documented-claim-behavior-v1', 'variant': args.variant,
              'executed_at_utc': datetime.now(timezone.utc).isoformat(),
              'runtime': {'python': platform.python_version(), 'implementation': platform.python_implementation(),
                          'optimize': sys.flags.optimize, 'debug': __debug__},
              'implementation': identity, 'entries': entries, 'returns': returns, 'cases': results,
              'render_calls': len(entries), 'strong_passes': sum(c['strong_case_passed'] for c in results),
              'weak_cancel_passes': sum(c['weak_cancel_status_passed'] is True for c in results),
              'gate_passed': all(c['strong_case_passed'] for c in results),
              'native_checker_run': False, 'customer_approval': 'not performed'}
    print(json.dumps(result, indent=2))
    return 0 if result['gate_passed'] else 1


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