"""Private native22 producer-combat probe; no AP server or delivery claim."""
import argparse
import hashlib
import importlib.util
import json
from pathlib import Path
import shutil
import sys
from types import SimpleNamespace

from test_gameplay_tutorial import initial_red_intro
from test_equipment_gate_route import GateRoute
from test_equipment_dirigibug import clear_dirigibugs, living_index


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


class ProbeRoute(GateRoute):
    def _command_with_movie_guard(self, op, fields, raw=False):
        fields = dict(fields)
        if op in ('squad_setup', 'squad_replace', 'effect_consumer_probe') or (op == 'actor_position' and fields['actor'] == 'navi'):
            fields['index' if op == 'actor_position' else 'captain'] = living_index(self.game.wait_state(lambda s: True))
        result = super()._command_with_movie_guard(op, fields, raw)
        if op == 'squad_replace' and getattr(self, '_cleanup_reserve', False):
            pod = next(o for o in result['onyons'] if o['type'] == 3)
            safe = super()._command_with_movie_guard('ground_query', dict(position=pod['position']))['last_result']['position']
            assert self.free_birth(0, safe)['last_result']['born'] == 1
            self.record('private-cleanup-free-pod-reserve', self.playable(), position=safe,
                boundary='one disclosed actual free Blue at native pod prevents cleanup-squad extinction; no health/actor revival')
        return result


def main(args):
    args.output.mkdir(parents=True, exist_ok=False)
    source = args.prepared.resolve()
    assert source.is_relative_to(Path(__file__).resolve().parents[1] / 'output')
    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')
    driver_path = args.output / 'executed-driver.py'; shutil.copyfile(args.driver, driver_path)
    spec = importlib.util.spec_from_file_location('dirigibug_executed_driver', driver_path)
    driver = importlib.util.module_from_spec(spec); spec.loader.exec_module(driver)
    tools = Path(__file__).resolve().parent
    inputs = {Path(__file__).resolve(), source/'profile.json', source/'bridge/runtime-config.json'}
    inputs.update(Path(m.__file__).resolve() for m in list(sys.modules.values())
        if getattr(m, '__file__', None) and Path(m.__file__).resolve().parent == tools)
    report = {'status':'running', 'boundary':__doc__, 'native_sha256':sha(args.native),
        'driver_sha256':sha(driver_path), 'input_sha256':{str(p):sha(p) for p in inputs}}
    for path, digest in report['input_sha256'].items():
        dst=args.output/'executed-inputs'/digest/Path(path).name;dst.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(path,dst)
    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
        report['entry']=initial_red_intro(game,driver)
        route=ProbeRoute(game,driver);route.scene(2,2036281396,3)
        native=copied/'bridge/native-state.json'
        before=json.loads(native.read_text())
        route.session=SimpleNamespace(ctx=SimpleNamespace(location_checks={(0,1):set(before['checks']),(0,2):set(before['checks'])}),
            native_journal=lambda slot:json.loads(native.read_text()))
        _,target,binding=route.physical(142)
        report['target_before']={'actor':target,'binding':binding}
        # Reuse the exact reviewed production-PAD geyser cleanup, bypassing
        # SurvivorRoute's independent bomb-bait glue to avoid recursion.
        route._cleanup_reserve = True
        try:
            GateRoute.clear_persistent_geysers(route,142,0)
        finally:
            route._cleanup_reserve = False
        report['evidence']=clear_dirigibugs(route,timeout=args.timeout)
        _,same,_=route.physical(142);assert same['actor_id']==target['actor_id']
        after=json.loads(native.read_text());assert before['checks']==after['checks'] and before['receipts']==after['receipts']
        report['AP_checks_and_receipts_unchanged']=True
        report['target_after']=same;report['status']='passed'
    except BaseException as error:
        report['status']='failed';report['failure']=f'{type(error).__name__}: {error}'[:2000]
        raise
    finally:
        report['last_state']=game.state(); report['trace']=getattr(locals().get('route'),'trace',[])
        game.shutdown();report['native_exit_code']=game.process.returncode if game.process else None
        report['inputs_unchanged']=all(sha(Path(p))==v for p,v in report['input_sha256'].items())
        (args.output/'report.json').write_text(json.dumps(report,indent=2)+'\n')


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