"""Production loaded-actor acceptance with explicit recruitment of added Pikmin.

This separate route preserves the currently executing normal/water/goal inputs.
All setup shortcuts are the same as LoadedRoute; ordinary cursor aim and whistle
recruit an additive Free Pikmin before it can participate in a carry threshold.
"""
from __future__ import annotations
import asyncio
import json
from test_gameplay_real_server import make_parser,run
from test_loaded_gameplay_real_server import LoadedRoute,SETUP
from test_real_server import until


class RecruitingRoute(LoadedRoute):
    def command(self,op,**fields):
        result=super().command(op,**fields)
        if op=='squad_setup':
            added=[p for p in result['pikis'] if p['navi_id']==0]
            if added:
                ids={p['actor_id'] for p in added}
                for _ in range(3):
                    state=self.playable()
                    live=[p for p in state['pikis'] if p['actor_id'] in ids]
                    center=[sum(p['position'][i] for p in live)/len(live) for i in range(3)]
                    self.driver.aim_at(self.game,center,radius=15)
                    self.game.input(buttons=self.driver.B,frames=120)
                    self.game.input(frames=8)
                    self.playable()
                owner=self.driver.active_navi(self.game.wait_state(lambda s:True))['actor_id']
                state=self.game.wait_state(lambda s:all(p['action']==0 and p['navi_id']==owner
                    for p in s['pikis'] if p['actor_id'] in ids),30,'actual additive Pikmin recruited into Formation')
                self.record('actual-additive-formation-recruitment',state,actor_ids=sorted(ids),owner=owner)
        return result

    def enemy_remote_case(self,location=72):
        before=self.scene(1,1717514292,0)
        before=self.command('actor_texture_baseline')
        audit=before['loaded']['actor_audit']
        assert audit['prototype_available']
        enemy=next(e for e in audit['enemies'] if e['location']==location and e['alive'] and e['health']>0)
        parked=next(a for a in audit['actors'] if a['location']==location)
        assert parked['pool_flags']&0x65 and not parked['alive'], 'expected real preborn parked enemy drop'
        previous={a['address']:a for a in audit['actors']}
        position=list(enemy['position']);position[0]-=50
        grounded=self.command('ground_query',position=position)['last_result']['position'];grounded[1]+=5
        self.command('actor_position',actor='navi',index=0,position=grounded)
        self.game.input(frames=20);self.playable()
        self.command('actor_defeat',location=location)
        self.playable()
        _,actor,binding=self.physical(location,120)
        assert binding['remote'] and binding['target']=='archipelago' and binding['min_carriers']==20
        spawned=self.game.wait_state(lambda s:True);after=spawned['loaded']['actor_audit']
        released=next(a for a in after['actors'] if a['location']==location)
        assert released['address']==parked['address'] and not released['pool_flags']&0x65 and released['alive']
        assert after['prototype_unchanged']
        remote=[a for a in after['actors'] if a['remote']]
        assert len(remote)>=2
        assert all(a['texture_table_private'] and a['collision_model_matches'] for a in remote)
        assert len({a['texture_table'] for a in remote})==len(remote)
        assert len({a['config_address'] for a in remote})==len(remote)
        for current in after['actors']:
            if current['address'] in previous:
                old=previous[current['address']]
                assert current['texture_table']==old['texture_table'] and current['texture_header_hash']==old['texture_header_hash']
        self.squad_at_actor(location,1,20)
        attached,_=self.attach(location,20)
        delivered=self.delivered(location,before)
        return dict(enemy_before=enemy,parked=parked,released=released,audit_before=audit,audit_after_drop=after,
            attached=attached,delivered=delivered,trace=self.trace.copy(),
            shortcuts=SETUP+['enemy health zero; actual death/drop, combat input bypassed'])


async def accept(session,driver):
    games={};routes={}
    for slot,configured in session.runs.items():
        game=driver.GameplayClient(session.args.native,session.args.assets,configured['profile'],
            configured['directory']/'loaded-control',configured['save'],session.output/f'loaded-{slot}.log')
        games[slot]=game;routes[slot]=RecruitingRoute(game,driver)
        session.register_cleanup(lambda current=game:asyncio.to_thread(current.shutdown))
        await asyncio.to_thread(game.start)
        session.event('loaded-normal-entry',slot=slot,route=await asyncio.to_thread(driver.boot_day1,game,timeout=300))
    local=await asyncio.to_thread(routes[1].carry_case,0,1952395313,1,10,1,5,'light_a',False)
    session.event('actual-own-four-blocked-five-carried',evidence=local)
    for slot in (1,2):await session.start_client(slot)
    await session.wait_checks({1:[10]});await session.wait_rewards()
    await asyncio.to_thread(games[2].shutdown)
    unavailable=session.native_journal(2)
    remote=await asyncio.to_thread(routes[1].carry_case,0,1952395313,0,9,1,20,'archipelago',True)
    session.event('actual-remote-nineteen-blocked-twenty-carried',evidence=remote)
    await session.wait_checks({1:[10,9]})
    queued_views=[]
    def queued():
        # The host checkpoints delivery transitions. While the real native
        # heartbeat is absent, indexed items remain in its memory queue and
        # the authoritative AP server history, before any journal transition.
        try:
            rows=(session.output/'client-2-initial.jsonl').read_text(encoding='utf8').splitlines()
            for line in rows:
                view=json.loads(line)
                if view.get('ap')=='Authenticated' and view.get('ledger',{}).get('queued')==len(session.expected_rewards()[2])>0:
                    queued_views.append(view)
                    return True
        except (OSError,ValueError,KeyError):return False
        return False
    await until(queued,'real remote reward queued while native endpoint absent',timeout=45)
    pending=session.client_journal(2)
    assert not any(record['state']=='Completed' for record in pending['snapshot']['records'])
    assert session.native_journal(2)==unavailable
    session.event('actual-native-endpoint-absent-generated-reward-queued',gui_view=queued_views[-1],
        journal=pending,native=unavailable,
        boundary='real GUI worker memory queue and authoritative AP history; no native application or Completed transition')
    cfg=session.runs[2]
    returned=driver.GameplayClient(session.args.native,session.args.assets,cfg['profile'],cfg['directory']/'return-control',
        cfg['save'],session.output/'loaded-2-return.log')
    games[2]=returned;routes[2]=RecruitingRoute(returned,driver)
    session.register_cleanup(lambda:asyncio.to_thread(returned.shutdown))
    await asyncio.to_thread(returned.start)
    recipient=asyncio.create_task(asyncio.to_thread(driver.boot_day1,returned,timeout=300))
    buried=await asyncio.to_thread(routes[1].carry_case,1,1717514289,0,49,4,25,'tel_dial',False,
        negative=False,buried=True)
    session.event('actual-white-dig-and-carry-buried-replacement',evidence=buried)
    session.event('actual-missing-endpoint-native-return',route=await recipient)
    await session.wait_checks({1:[10,9,49]});await session.wait_rewards()
    enemy=await asyncio.to_thread(routes[2].enemy_remote_case)
    session.event('actual-enemy-drop-private-ap-model-and-carry',evidence=enemy)
    await session.wait_checks({2:[72]});await session.wait_rewards()
    native={}
    for slot,game in games.items():
        state=await asyncio.to_thread(game.wait_state,lambda s:True);session.assert_native_reward_state(slot,state)
        native[str(slot)]=state
    session.mark_gate('physical_replacements',True,dict(local=local,remote=remote,buried=buried,enemy=enemy),
        SETUP+['enemy health zero; native FSM death/drop animation, combat input bypassed'])
    session.mark_gate('local_remote_delivery',True,dict(native=native,rewards=session.expected_rewards()),SETUP)
    before={s:session.native_journal(s) for s in (1,2)}
    revisit=await asyncio.to_thread(routes[1].scene,0,1952395313,1)
    assert not any(p['location_id']==10 for p in revisit['pellets'])
    await session.reconnect();await session.wait_rewards()
    for slot,game in games.items():
        current=session.native_journal(slot)
        assert current['receipts']==before[slot]['receipts'] and current['checks']==before[slot]['checks']
        session.assert_native_reward_state(slot,await asyncio.to_thread(game.wait_state,lambda s:True))
    session.mark_gate('reconnect',True,dict(before=before,after={s:session.native_journal(s) for s in (1,2)},
        missing_endpoint={'queued_gui_view':queued_views[-1],'pending':pending,'native':unavailable},revisit=revisit),SETUP)


if __name__=='__main__':
    asyncio.run(run(make_parser(__doc__).parse_args(),acceptance=accept,
        scope_gates=('physical_replacements','local_remote_delivery','reconnect'),
        acceptance_kind='loaded_scene',boundary=__doc__))
