"""One-slot real Red combat and White equipment dig/carry preflight, no AP-server gate."""
import argparse
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
from test_gameplay_digging_cases import DiggingRoute,prepare_digging_squad
from test_gameplay_hiba_combat import clear_hiba_with_reds
from test_gameplay_tutorial import initial_red_intro
from test_real_server import sha


class Route(DiggingRoute):
    def journal(self):return json.loads((self.bridge/'native-state.json').read_text())
    def clear_hob_geysers(self,location):
        self.combat=clear_hiba_with_reds(self,location,self.journal)


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    for option in ('native','client','assets','output'):parser.add_argument('--'+option,type=Path,required=True)
    args=parser.parse_args();root=args.output.resolve();root.mkdir(parents=True,exist_ok=False)
    base=Path(__file__).resolve().parents[1];patch=next((base/'tests/fixtures/pokos280-2026101503/generated').glob('*_P2_*.appik2'));run=root/'run'
    prepared=subprocess.run([str(args.client.resolve()),'prepare',str(patch),'--endpoint','ws://127.0.0.1:9',
        '--run-dir',str(run),'--save','native-hiba-red-preflight'],capture_output=True,text=True)
    assert prepared.returncode==0,prepared.stderr
    source=base.parent/'native/tools/test_gameplay_control.py';frozen=root/'executed-driver.py';frozen.write_bytes(source.read_bytes())
    spec=importlib.util.spec_from_file_location('hiba_driver',frozen);driver=importlib.util.module_from_spec(spec);sys.modules[spec.name]=driver;spec.loader.exec_module(driver)
    names=('test_hiba_red_native_preflight.py','test_gameplay_hiba_combat.py','test_gameplay_digging_cases.py',
        'test_equipment_survivors.py','test_equipment_gameplay_real_server.py','test_gameplay_grounded_cases.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(base/'tools'/n):sha(base/'tools'/n) for n in names}
    game=driver.GameplayClient(args.native,args.assets,run/'profile.json',root/'control',run/'save',root/'native.log')
    report={'status':'failed','boundary':__doc__,'accepted_AP_gates':[],'ap_server_present':False,
        'native_sha256':sha(args.native),'driver_sha256':sha(frozen),'patch_sha256':sha(patch),'helper_sha256':pins}
    try:
        game.start();report['entry']=initial_red_intro(game,driver)
        route=Route(game,driver);route.bridge=run/'bridge';before=route.scene(1,1717514289,2)
        report['cleanup']=clear_hiba_with_reds(route,51,route.journal)
        _,actor,binding=route.physical(51);report['binding']=binding
        # The hazards are gone; avoid replaying cleanup while recruiting Whites.
        route.clear_hob_geysers=lambda location:None
        prepare_digging_squad(route,51,4,min(100,max(2,binding['min_carriers']*2)))
        report['attached']=route.attach(51,binding['min_carriers'])[0]
        report['after']=route.delivered(51,before,300);report['trace']=route.trace
        journal=route.journal();assert journal['checks']==[51] and not journal['receipts']
        report['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())
        if not report['inputs_unchanged']:report['status']='failed'
        (root/'report.json').write_text(json.dumps(report,indent=2)+'\n')
