"""Reproduce a test-setup stall and retain only that test-owned child for gdb.

This is diagnostic only; it has no AP server or gameplay acceptance claim.
"""
import argparse
import importlib.util
import json
from pathlib import Path
import subprocess
import sys
from test_loaded_gameplay_real_server import LoadedRoute
from test_real_server import sha


def main(args):
    args.output.mkdir(parents=True,exist_ok=False)
    frozen=args.output/'executed-driver.py';frozen.write_bytes(args.driver.read_bytes())
    spec=importlib.util.spec_from_file_location('held_gameplay_driver',frozen)
    driver=importlib.util.module_from_spec(spec);sys.modules[spec.name]=driver;spec.loader.exec_module(driver)
    run=args.output/'run'
    subprocess.run([str(args.client.resolve()),'prepare',str(args.patch.resolve()),'--endpoint','ws://127.0.0.1:1',
        '--run-dir',str(run.resolve()),'--save','test-owned-stall-probe'],check=True,capture_output=True)
    game=driver.GameplayClient(args.native,args.assets,run/'profile.json',run/'control',run/'save',args.output/'native.log')
    keep=False
    try:
        game.start();driver.boot_day1(game,timeout=300)
        route=LoadedRoute(game,driver)
        route.scene(0,1952395313,0)
        route.squad_at_actor(8,1,20)
        (args.output/'result.json').write_text(json.dumps({'status':'not_reproduced','state':game.wait_state(lambda s:True)},indent=2)+'\n')
    except TimeoutError:
        last=game.wait_state(lambda s:True)
        if game.process.poll() is None and last and last.get('response_id',0)<game.sequence:
            keep=True
            receipt={'status':'diagnostic_stall_held','pid':game.process.pid,'native_sha256':sha(args.native),
                'control_dir':str(game.control_dir),'log':str(game.log_path),'state':last,'pending_sequence':game.sequence,
                'boundary':'test-owned native remains alive solely for scoped debugger stack capture; no acceptance credit'}
            (args.output/'held-process.json').write_text(json.dumps(receipt,indent=2)+'\n')
            print(json.dumps({k:receipt[k] for k in ('status','pid','control_dir')},indent=2),flush=True)
        raise
    finally:
        if not keep:game.shutdown()


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