"""Measure real PAD punch edges on a private copy of an earned Knuckles run.

No AP server is started: this diagnostic reuses the validated native receipt
journal earned by the official real-server scope. It is not a new AP gate.
"""
import argparse
import hashlib
import importlib.util
import json
from pathlib import Path
import shutil
import sys
import time

from test_gameplay_tutorial import initial_red_intro
from test_gameplay_settled_route import SettledRoute


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def view(state):
    return {k:state.get(k) for k in ('response_id','retrace','input_remaining','equipment','ready',
        'movie_state','paused','ui_scene','navi')} | {'captains':state.get('effects',{}).get('captains',[])}


def main(args):
    args.output.mkdir(parents=True,exist_ok=False)
    metadata=json.loads(args.checkpoint.read_text())
    source=Path(metadata['runs']['2']['directory'])
    root=Path(__file__).resolve().parents[1]/'output'
    assert source.resolve().is_relative_to(root.resolve())
    report={'status':'running','boundary':__doc__,'checkpoint_sha256':sha(args.checkpoint),
        'native_sha256':sha(args.native),'source_run':str(source),'samples':[],'streams':[]}
    assert report['native_sha256']==metadata['native_sha256']
    driver_path=args.output/'executed-driver.py'
    shutil.copyfile(args.driver,driver_path)
    sys.path.insert(0,str(args.driver.parent))
    spec=importlib.util.spec_from_file_location('punch_executed_driver',driver_path)
    driver=importlib.util.module_from_spec(spec);spec.loader.exec_module(driver)
    helper_paths=[args.driver,Path(__file__),Path(__file__).with_name('test_gameplay_tutorial.py'),
        Path(__file__).with_name('test_gameplay_settled_route.py'),Path(__file__).with_name('test_gameplay_routes.py'),
        Path(__file__).with_name('test_loaded_gameplay_recruitment.py'),Path(__file__).with_name('test_loaded_gameplay_real_server.py')]
    report['helpers']={str(p.resolve()):sha(p) for p in helper_paths}
    copied=args.output/'prepared-run'
    shutil.copytree(source,copied,ignore=shutil.ignore_patterns('*.lock','*.tmp'))
    profile_path=copied/'profile.json';profile=json.loads(profile_path.read_text())
    profile['bridge_dir']=str((copied/'bridge').resolve());profile['journal_path']=str((copied/'journal.json').resolve())
    profile_path.write_text(json.dumps(profile,indent=2)+'\n')
    native_state=copied/'bridge/native-state.json'
    report['earned_journal_sha256']=sha(native_state)
    game=driver.GameplayClient(args.native,args.assets,profile_path,args.output/'control',copied/'save',args.output/'native.log')
    try:
        game.start();report['pid']=game.process.pid
        entry=initial_red_intro(game,driver)
        (args.output/'entry.json').write_text(json.dumps(entry))
        route=SettledRoute(game,driver);route.scene(0)
        position=route.command('ground_query',position=[-320,5,2915])['last_result']['position'];position[1]+=5
        route.command('actor_position',actor='navi',index=0,position=position)
        game.input(frames=90);before=route.playable()
        assert before['equipment']&1 and not before['pikis']
        report['before']=view(before)
        # The ordinary per-command API waits for 100ms snapshot publication.
        # Stream existing atomic input requests instead; two retraces of A
        # expire to neutral before the next request. No FSM/effect setters.
        for spacing in (.065,.085,.115):
            start=time.monotonic();observed=-1
            for index in range(100):
                game.sequence+=1
                payload={'id':game.sequence,'op':'input','buttons':driver.A,'frames':2,
                    'stick_x':0,'stick_y':0,'cstick_x':0,'cstick_y':0}
                temp=game.control_dir/'stream.tmp';temp.write_text(json.dumps(payload))
                deadline=time.monotonic()+2
                while True:
                    try:temp.replace(game.control_dir/'control.json');break
                    except PermissionError:
                        if time.monotonic()>deadline:raise
                        time.sleep(.002)
                report['streams'].append({'seconds':time.monotonic()-start,'spacing':spacing,'request':payload})
                state=game.state()
                if state and state['response_id']!=observed:
                    observed=state['response_id'];report['samples'].append(view(state))
                    if max(c['punch_combo_max_observed'] for c in state['effects']['captains'])>=2:break
                time.sleep(max(0,start+(index+1)*spacing-time.monotonic()))
            final=game.input(frames=30)
            report['samples'].append(view(final))
            if max(c['punch_combo_max_observed'] for c in final['effects']['captains'])>=2:
                report['successful_spacing']=spacing;break
        report['after']=view(final)
        assert max(c['punch_combo_max_observed'] for c in final['effects']['captains'])>=2
        report['status']='passed'
    except BaseException as error:
        report['status']='failed';report['failure']=f'{type(error).__name__}: {error}'[:2000]
        raise
    finally:
        game.shutdown();report['native_exit_code']=game.process.returncode if game.process else None
        report['source_journal_unchanged']=sha(source/'bridge/native-state.json')==report['earned_journal_sha256']
        report['helpers_unchanged']=all(sha(Path(p))==digest for p,digest in report['helpers'].items())
        (args.output/'report.json').write_text(json.dumps(report,indent=2)+'\n')


if __name__=='__main__':
    parser=argparse.ArgumentParser(__doc__)
    for name in ('checkpoint','output','native','assets','driver'):parser.add_argument('--'+name,type=Path,required=True)
    main(parser.parse_args())
