"""Two selected attempts per group; run only through reproduce.py or --group."""
import argparse
import copy
from datetime import datetime, timezone
import hashlib
import inspect
import json
from pathlib import Path
import platform
import sys

from note_service import NoteService, AlwaysDenyControl
import strong_witness

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


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--group', required=True,
                        choices=['weak_helper', 'corrected_public', 'always_deny_control'])
    args = parser.parse_args()
    cases = json.loads((HERE / 'cases.json').read_text())
    functions = [NoteService._append_note, NoteService.submit_note, AlwaysDenyControl.submit_note]
    identities = {}
    for function in functions:
        identities[function.__code__] = {
            'function': function.__module__ + '.' + function.__qualname__,
            'file': 'note_service.py',
            'file_sha256': hashlib.sha256((HERE / 'note_service.py').read_bytes()).hexdigest(),
            'function_source_sha256': hashlib.sha256(inspect.getsource(function).encode()).hexdigest(),
            'first_line': function.__code__.co_firstlineno}
    entries, returns, results = [], [], []
    phase, depth = None, 0

    def profile(frame, event, arg):
        nonlocal depth
        identity = identities.get(frame.f_code)
        if identity is None:
            return
        if event == 'call':
            entries.append({'case': phase, 'depth': depth, **identity,
                            'role': frame.f_locals['role'], 'text': frame.f_locals['text']})
            depth += 1
        elif event == 'return':
            depth -= 1
            returns.append({'case': phase, 'depth': depth, **identity, 'reply': copy.deepcopy(arg)})

    if sys.getprofile() is not None:
        raise RuntimeError('Use an unprofiled interpreter')
    try:
        sys.setprofile(profile)
        for case in cases:
            phase = case['id']
            service = AlwaysDenyControl() if args.group == 'always_deny_control' else NoteService()
            before = copy.deepcopy(service.notes)
            if not strong_witness.exact_equal(before, case['before_notes']):
                raise RuntimeError('Literal fresh starting notes differ')
            function = (service._append_note if args.group == 'weak_helper' and
                        phase == 'viewer_attempt' else service.submit_note)
            reply = function(case['role'], case['text'])
            actual = {'entry_name': function.__name__, 'actor_argument': case['role'],
                      'reply': reply, 'notes': copy.deepcopy(service.notes)}
            witness = (strong_witness.matches_public_viewer if phase == 'viewer_attempt'
                       else strong_witness.matches_editor_control)
            strong = witness(actual)
            if strong != strong_witness.exact_equal(actual, case['expected']):
                raise RuntimeError('Witness disagrees with independent literal table')
            results.append({'id': phase, 'role': case['role'], 'text': case['text'],
                            'called_function': function.__func__.__module__ + '.' + function.__func__.__qualname__,
                            'before_notes': before, 'actual': actual, 'expected': case['expected'],
                            'strong_case_passed': strong,
                            'weak_viewer_created_observation': reply.get('status') == 'created'
                            if phase == 'viewer_attempt' else None})
    finally:
        sys.setprofile(None)
    if depth != 0 or len(entries) != len(returns):
        raise RuntimeError('Incomplete selected function trace')
    result = {'schema': 'poc-quality-local-behavior-v1', 'group': args.group,
              'executed_at_utc': datetime.now(timezone.utc).isoformat(),
              'runtime': {'python': platform.python_version(), 'implementation': platform.python_implementation(),
                          'optimize': sys.flags.optimize, 'debug': __debug__},
              'source_sha256': {name: hashlib.sha256((HERE / name).read_bytes()).hexdigest()
                                for name in ['note_service.py', 'strong_witness.py', 'cases.json', 'run_behavior.py']},
              'profile_match': 'Exact imported Python frame.f_code identity; nested helper calls retained separately',
              'entries': entries, 'returns': returns, 'cases': results,
              'selected_attempts': len(results), 'profiled_entries': len(entries),
              'profiled_returns': len(returns),
              'strong_passes': sum(x['strong_case_passed'] for x in results),
              'gate_passed': all(x['strong_case_passed'] for x in results),
              'native_checker_run': False, 'authentication': 'not implemented',
              'interpretation': 'Corrected PoC/claim, not product repair; successful viewer denial means no local public-method exploit reproduced'}
    print(json.dumps(result, indent=2))
    return 0 if result['gate_passed'] else 1


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