"""Later-scene actor routes against the original two-slot AP server.

This deliberately does not satisfy normal entry, first-day carrying, ordinary
campaign travel or MemoryCard gates. Setup loads real SGS scenes and creates a
real squad, then all attachment, carry AI, digging and delivery stay game-owned.
"""
from __future__ import annotations
import asyncio
import json
import math
import time
from test_gameplay_real_server import make_parser, run

SETUP = [
    'normal story boot followed by test-only scene/day selection through production SGS_Load',
    'test-only real squad replacement; reproduction and Onion withdrawal bypassed',
    'captain positioned beside the authored actor; pellet remains at authored position',
]


class LoadedRoute:
    def __init__(self, game, driver):
        self.game, self.driver, self.trace = game, driver, []

    def record(self, label, state=None, **fields):
        state = state or self.game.wait_state(lambda s: True)
        self.trace.append(dict(label=label, state=state, **fields))
        return state

    def command(self, op, **fields):
        deadline=time.monotonic()+180
        for attempt in range(8):
            try:
                state=self.game.command(op,timeout=max(1,deadline-time.monotonic()),**fields)
            except RuntimeError as error:
                detail=str(error).removeprefix('native gameplay harness: ')
                if not detail.startswith('test mutation busy:'):raise
                if time.monotonic()>=deadline:raise
                # Busy is an acknowledged refusal, never a completed mutation.
                # Clear that response with a real acknowledged state command,
                # then let ordinary PAD/movie policy restore a safe boundary.
                cleared=self.game.command('state',timeout=max(1,deadline-time.monotonic()))
                self.record('test-mutation-busy',cleared,request=dict(op=op,**fields),error=detail,attempt=attempt+1)
                self.playable(timeout=max(1,deadline-time.monotonic()))
                continue
            self.record(op,state,request=fields)
            return state
        raise TimeoutError(f'bounded native mutation retries exhausted: {op}')

    def playable(self, timeout=120, **identity):
        deadline = time.monotonic() + timeout
        while time.monotonic() < deadline:
            state = self.game.wait_state(lambda s: True)
            if state.get('ready') and state.get('movie_state',0)==0 and all(state.get(k) == v for k,v in identity.items()):
                return self.record('loaded-playable', state)
            if state.get('movie_pause'):
                self.game.press(self.driver.START)
            elif state.get('paused'):
                self.game.press(self.driver.A)
            else:
                self.game.input(frames=20)
        raise TimeoutError(f'actual scene failed to become playable: {self.trace[-3:]}')

    def scene(self, course, cave=0, floor=0):
        current=self.playable()
        if cave and not current['pikis']:
            self.command('squad_setup',color=1,count=1,captain=0)
            self.game.input(buttons=self.driver.B,frames=12)
            self.game.input(frames=8)
            current=self.playable()
            assert current['pikis'], 'real cave setup requires a surviving native squad'
        self.command('scene_setup', course=course, cave=cave, floor=floor, day=4)
        self.game.wait_state(lambda s:s.get('game_state') == 2 or not s.get('ready'), 30,
                             'actual SGS_Load transition')
        state = self.playable(course=course,cave=cave,**({'floor':floor} if cave else {}))
        # Later-map setup still runs the real authored Onion discovery while
        # its wild Pikmin exist. Killing them first leaves the demo's real
        # target absent. No demo/story flags are assigned by this route.
        if not cave and course in (1,2):
            color=0 if course==1 else 2
            onion=next(o for o in state['onyons'] if o['type']==color)
            position=list(onion['position'])
            position[0]-=100
            position[1]+=10
            self.command('actor_position',actor='navi',index=0,position=position)
            self.game.input(frames=20)
            state=self.playable(course=course,cave=0)
            self.record('authored-onion-intro-completed-before-squad-clear',state,color=color)
        if not cave:
            self.command('squad_clear')
            state = self.game.wait_state(lambda s:not s.get('pikis'), 30, 'real squad cleared for exact carrier count')
        else:
            assert state['pikis'], 'actual cave load lost every prepared Pikmin before the route could begin'
        return self.record('clean-real-scene', state)

    def physical(self, location, timeout=30):
        def released(s):
            live=any(p['location_id']==location for p in s.get('pellets',[]))
            actor_audit=s.get('loaded',{}).get('actor_audit',{})
            audit=actor_audit.get('actors',[])
            held={e.get('held_pellet',0) for e in actor_audit.get('enemies',[])}-{0}
            bindings=[b for b in s.get('loaded',{}).get('physical',[]) if b['location']==location]
            buried=bool(bindings and bindings[0]['depth_max']>0)
            # Underground capture is the actual dig prerequisite, distinct
            # from a still-held enemy/boss actor. Parked pool flags stay strict.
            parked=any(a['location']==location and (a['pool_flags']&0x65
                or (a.get('captured_now',False) and (not buried or a['address'] in held))) for a in audit)
            return live and not parked
        state = self.game.wait_state(released,
                                     timeout, f'authored live pellet {location}')
        actor = next(p for p in state['pellets'] if p['location_id']==location)
        binding = next(p for p in state['loaded']['physical'] if p['location']==location)
        assert binding['collision_model_matches'], binding
        assert actor['minimum']==binding['min_carriers']
        return state, actor, binding

    def squad_at_actor(self, location, color, count):
        state, actor, binding = self.physical(location)
        # No pellet relocation: only the captain and fresh squad setup position.
        position = list(actor['position'])
        position[0] -= 80
        position[1] += 10
        self.command('actor_position',actor='navi',index=0,position=position)
        self.game.input(frames=20)
        self.playable()
        born = self.command('squad_replace',color=color,count=count,captain=0,position=position)
        assert born['last_result']['born']==count
        for _ in range(3):
            state=self.playable()
            center=[sum(p['position'][i] for p in state['pikis'])/len(state['pikis']) 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()
        state=self.game.wait_state(lambda s:len(s.get('pikis',[]))==count,30,'exact live squad')
        assert all(p['kind']==color for p in state['pikis'])
        owner=self.driver.active_navi(state)['actor_id']
        state=self.game.wait_state(lambda s:len(s.get('pikis',[]))==count
            and all(p['kind']==color and p['action']==0 and p['navi_id']==owner for p in s['pikis']),
            15,'actual whistled Formation Pikmin, not wild enemy-parent actors')
        self.record('actual-owned-formation-squad',state,color=color,count=count,owner=owner)
        return actor,binding

    def aim(self, state, actor):
        navi=self.driver.active_navi(state)
        delta=[actor['position'][i]-navi['position'][i] for i in (0,2)]
        length=math.hypot(*delta)
        if length<1:return 0,80
        dx,dz=(d/length for d in delta)
        side,front=navi['camera_side'],navi['camera_front']
        sn,fn=math.hypot(side[0],side[2]),math.hypot(front[0],front[2])
        return round(-100*(dx*side[0]+dz*side[2])/sn),round(100*(dx*front[0]+dz*front[2])/fn)

    def attach(self, location, power, timeout=90):
        deadline=time.monotonic()+timeout
        while time.monotonic()<deadline:
            state,actor,_=self.physical(location)
            self.record('carrier-progress',state,location=location)
            if actor['carry_power']>=power:
                return state,actor
            self.driver.walk_to(self.game,actor['position'],radius=65,timeout=30)
            state,actor,_=self.physical(location)
            x,y=self.aim(state,actor)
            self.game.input(frames=75,cstick_x=x,cstick_y=y)
            for _ in range(4):self.game.press(self.driver.A,frames=3)
        raise TimeoutError(f'actual Pikmin did not attach at {location}; last {self.trace[-3:]}')

    def delivered(self, location, baseline, timeout=180):
        def arrived(state):
            if isinstance(baseline,dict):
                if 'physical_deliveries' in state and 'physical_deliveries' in baseline:
                    return state['physical_deliveries'].get(str(location),0)>baseline['physical_deliveries'].get(str(location),0)
                old=baseline['delivery_count']
            else:old=baseline
            return state.get('delivery_count',0)>old and state.get('last_delivery_location')==location
        state=self.game.wait_state(arrived,timeout,f'actual Onyon arrival for {location}')
        return self.record('actual-delivery',state,location=location)

    def enemy_remote_case(self, location=5):
        self.scene(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)
        previous={a['address']:a for a in audit['actors']}
        position=list(enemy['position'])
        position[0]-=150
        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)
        assert binding['remote'] and binding['target']=='archipelago' and binding['min_carriers']==20
        spawned=self.game.wait_state(lambda s:any(a['location']==location for a in s['loaded']['actor_audit']['actors']))
        after=spawned['loaded']['actor_audit']
        assert after['prototype_unchanged'], 'real enemy AP model changed shared blue-marble prototype'
        remote=[a for a in after['actors'] if a['remote']]
        assert len(remote)>=2, 'need simultaneously alive AP replacement actors'
        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,audit_before=audit,audit_after_drop=after,
            attached=attached,delivered=delivered,trace=self.trace.copy(),
            shortcuts=SETUP+['enemy health set0; native FSM death/drop animation exercised; battle input bypassed'])

    def carry_case(self, course, cave, floor, location, color, minimum, text, remote,
                   negative=True, buried=False):
        before=self.scene(course,cave,floor)
        actor,binding=self.squad_at_actor(location,color,minimum-1 if negative else minimum)
        assert binding['target']==text and binding['remote'] is remote, binding
        assert binding['min_carriers']==minimum, binding
        if buried:assert binding['depth_max']>0 and binding['depth']>0, binding
        initial=actor['position']
        baseline=before['delivery_count']
        if negative:
            self.attach(location,minimum-1)
            self.game.input(frames=150)
            state,actor,_=self.physical(location)
            assert actor['carry_power']==minimum-1, actor
            assert self.driver.distance(initial,actor['position'])<40, 'underweight actor travelled'
            assert state['delivery_count']==baseline
            self.record('insufficient-carriers-blocked',state,required=minimum,observed=minimum-1)
            self.command('squad_setup',color=color,count=1,captain=0,
                         position=self.driver.active_navi(state)['position'])
        attached,_=self.attach(location,minimum)
        after=self.delivered(location,before)
        self.playable()
        return dict(location=location,binding=binding,attached=attached,after=after,
                    shortcuts=SETUP,trace=self.trace.copy())


async def run_loaded(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
        session.register_cleanup(lambda current=game:asyncio.to_thread(current.shutdown))
        await asyncio.to_thread(game.start)
        entry=await asyncio.to_thread(driver.boot_day1,game,timeout=240)
        session.event('loaded-route-normal-boot',slot=slot,state=entry['state'])
        routes[slot]=LoadedRoute(game,driver)
    # The normal route handles the intact overworld paper bag. This later
    # weight test uses the authored cave actor without bypassing that obstacle.
    local=await asyncio.to_thread(routes[1].carry_case,0,1952395313,1,10,1,5,'light_a',False)
    session.event('loaded-own-weight-model-carry',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_before=session.native_journal(2)
    remote=await asyncio.to_thread(routes[1].carry_case,0,1952395313,0,9,1,20,'archipelago',True)
    session.event('loaded-remote-weight-model-carry',evidence=remote)
    await session.wait_checks({1:[10,9]})
    from test_real_server import until
    def queued():
        try:return len(session.client_journal(2)['snapshot']['records'])==len(session.expected_rewards()[2])
        except (OSError,ValueError,KeyError):return False
    await until(queued,'generated remote reward queued while actual native endpoint absent',timeout=30)
    pending=session.client_journal(2)
    records=pending['snapshot']['records']
    assert records and records[-1]['state']!='Completed'
    assert session.native_journal(2)==unavailable_before
    session.event('missing-real-native-endpoint',journal=pending,native=unavailable_before)
    configured=session.runs[2]
    returned=driver.GameplayClient(session.args.native,session.args.assets,configured['profile'],
        configured['directory']/'loaded-control-return',configured['save'],session.output/'loaded-2-return.log')
    games[2]=returned
    session.register_cleanup(lambda:asyncio.to_thread(returned.shutdown))
    await asyncio.to_thread(returned.start)
    recipient_boot=asyncio.create_task(asyncio.to_thread(driver.boot_day1,returned,timeout=240))
    buried=await asyncio.to_thread(routes[1].carry_case,1,0,0,43,4,5,'toy_ring_a_red',False,
                                  negative=False,buried=True)
    session.event('loaded-white-dig-model-carry',evidence=buried)
    session.event('missing-endpoint-native-return',route=await recipient_boot)
    await session.wait_checks({1:[10,9,43]})
    await session.wait_rewards()
    routes[2]=LoadedRoute(returned,driver)
    enemy=await asyncio.to_thread(routes[2].enemy_remote_case)
    session.event('real-enemy-remote-drop-private-model-carry',evidence=enemy)
    await session.wait_checks({2:[5]})
    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
    assert any(r['source']==1 and r['location']==9 and r['item_id']==511
               for r in session.expected_rewards()[2])
    session.mark_gate('physical_replacements',True,dict(local=local,remote=remote,buried=buried,enemy=enemy),
        SETUP+['enemy health set0; native FSM death/drop animation exercised; battle input bypassed'])
    session.mark_gate('local_remote_delivery',True,dict(native=native,rewards=session.expected_rewards()),SETUP,
        remaining=None)
    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']), 'collected real cave actor respawned'
    session.event('actual-scene-revisit-no-duplicate-actor',state=revisit)
    await session.reconnect()
    await session.wait_rewards()
    for slot in (1,2):
        after=session.native_journal(slot)
        assert after['receipts']==before[slot]['receipts'] and after['checks']==before[slot]['checks']
        session.assert_native_reward_state(slot,await asyncio.to_thread(games[slot].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={'pending':pending,'native_before':unavailable_before},revisit=revisit),SETUP)


if __name__=='__main__':
    args=make_parser(__doc__).parse_args()
    asyncio.run(run(args,acceptance=run_loaded,
        scope_gates=('physical_replacements','local_remote_delivery','reconnect'),
        acceptance_kind='loaded_scene',
        boundary='real engine scenes and live actor carrying/digging/Onyon delivery, original-world AP server and production companion; direct scene, squad and captain setup explicitly bypass campaign travel and acquisition'))
