"""Bounded native grounding/dig/carry probe; no AP-server or accepted AP-gate claim."""
import argparse
import importlib.util
import json
from pathlib import Path
import subprocess
import time
from test_gameplay_grounded_cases import GroundedLoadedRoute
from test_equipment_survivors import NearConsumerRoute
from test_gameplay_tutorial import initial_red_intro
from test_real_server import sha


class ProbeRoute(GroundedLoadedRoute):
    def journal(self):return json.loads((self.bridge/'native-state.json').read_text())
    def clear_hob_geysers(self,location):
        if location!=51:return
        before=self.journal();baseline=self.playable()['physical_deliveries'];cleaned=[]
        for _ in range(24):
            state=self.playable();live=[e for e in state['loaded']['actor_audit']['live_enemies'] if e['location']<1 and e['alive']]
            if not live or live[0]['enemy_id']!=20:break
            enemy=live[0];position=list(enemy['position']);position[0]-=35;position[1]+=5
            self.command('actor_position',actor='navi',index=0,position=position);self.game.input(frames=20);state=self.playable()
            first=next(e for e in state['loaded']['actor_audit']['live_enemies'] if e['location']<1 and e['alive'])
            assert first['enemy_id']==20 and self.driver.distance(first['position'],enemy['position'])<1
            self.command('actor_defeat',location=-1);deadline=time.monotonic()+30
            while time.monotonic()<deadline:
                self.game.input(frames=30);state=self.playable()
                if not any(e['alive'] and e['enemy_id']==20 and self.driver.distance(e['position'],enemy['position'])<1
                    for e in state['loaded']['actor_audit']['live_enemies']):break
            else:raise TimeoutError('actual Hiba FSM did not finish death')
            assert state['physical_deliveries']==baseline;cleaned.append(enemy)
        else:raise AssertionError('Hiba cleanup limit')
        after=self.journal();assert before['checks']==after['checks'] and before['receipts']==after['receipts']
        self.record('native-only-targeted-hiba-cleanup',state,cleaned=cleaned,
            boundary='exact Hiba20 health0/native FSM; no APserver present; no combat caller claim')


def main(args):
    root=args.output.resolve();root.mkdir(parents=True,exist_ok=False)
    original=Path(__file__).resolve().parents[1]/'tests/fixtures/pokos280-2026101503/generated'
    patch=next(original.glob('*_P1_*.appik2'));run=root/'run'
    result=subprocess.run([str(args.client.resolve()),'prepare',str(patch),'--endpoint','ws://127.0.0.1:9',
        '--run-dir',str(run),'--save','grounded-native-preflight'],capture_output=True,text=True)
    assert result.returncode==0,result.stderr
    source=Path(__file__).resolve().parents[2]/'native/tools/test_gameplay_control.py'
    frozen=root/'executed-driver.py';frozen.write_bytes(source.read_bytes())
    spec=importlib.util.spec_from_file_location('preflight_driver',frozen);driver=importlib.util.module_from_spec(spec);spec.loader.exec_module(driver)
    helpers=[Path(__file__).resolve()]+[Path(__file__).with_name(n) for n in ('test_gameplay_grounded_cases.py',
        'test_equipment_survivors.py','test_equipment_gameplay_real_server.py','test_gameplay_carriers.py',
        'test_gameplay_tutorial.py','test_gameplay_settled_route.py','test_gameplay_routes.py',
        'test_loaded_gameplay_recruitment.py','test_loaded_gameplay_real_server.py')]
    pins={str(p):sha(p) for p in helpers};game=driver.GameplayClient(args.native,args.assets,run/'profile.json',root/'control',run/'save',root/'native.log')
    report={'status':'failed','boundary':__doc__,'native_sha256':sha(args.native),'driver_sha256':sha(frozen),
        'patch_sha256':sha(patch),'helper_sha256':pins,'ap_server_present':False,'accepted_AP_gates':[]}
    try:
        game.start();report['entry']=initial_red_intro(game,driver)
        route=ProbeRoute(game,driver);route.bridge=run/'bridge'
        report['buried']=route.carry_case(1,1717514289,0,49,4,25,'tel_dial',False,negative=False,buried=True)
        before=route.scene(1,1717514289,2);route.clear_hob_geysers(51)
        _,actor,binding=route.physical(51)
        NearConsumerRoute.squad_at_actor(route,51,4,min(100,max(2,binding['min_carriers']*2)))
        attached,_=route.attach(51,binding['min_carriers']);arrived=route.delivered(51,before,300)
        report['hiba_carry']={'binding':binding,'attached':attached,'arrived':arrived,'trace':route.trace}
        journal=route.journal();assert set(journal['checks'])=={49,51} and not journal['receipts']
        report['native_journal']=journal;report['status']='passed'
    except BaseException as error:
        report['failure']=f'{type(error).__name__}: {error}';raise
    finally:
        game.shutdown();report['inputs_unchanged']=all(sha(Path(p))==digest for p,digest in pins.items())
        (root/'report.json').write_text(json.dumps(report,indent=2)+'\n')


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