"""Loaded actor routes with the normal movie/appraisal input policy.

Setup boundaries remain RecruitingRoute's explicit later-scene preparation.
Native menus, movies and appraisals are answered through ordinary PAD input.
"""
import time
from test_loaded_gameplay_recruitment import RecruitingRoute


class StableRoute(RecruitingRoute):
    def playable(self,timeout=150,**identity):
        deadline=time.monotonic()+timeout
        while time.monotonic()<deadline:
            state=self.driver.live_scene(self.game,timeout=max(1,deadline-time.monotonic()))
            if all(state.get(k)==v for k,v in identity.items()):
                return self.record('loaded-playable',state)
            self.game.input(frames=20)
        raise TimeoutError(f'actual playable scene has wrong identity: {identity}')

    def clear_snow_enemies(self):
        """Isolate carrier weights from unrelated Snow Bulborb combat.

        The existing generic selector targets the first live non-check enemy.
        Verify its actual type45 before every bounded health stimulus. Never
        affect a treasure holder, Candypop or boss; actual death stays native.
        """
        for _ in range(16):
            before=self.playable()
            enemies=[e for e in before['loaded']['actor_audit']['live_enemies']
                     if e['location']<1 and e['alive']]
            if not enemies or enemies[0]['enemy_id']!=45:break
            enemy=enemies[0]
            position=list(enemy['position']);position[0]-=50
            position=self.command('ground_query',position=position)['last_result']['position'];position[1]+=5
            self.command('actor_position',actor='navi',index=0,position=position)
            self.game.input(frames=20);self.playable()
            current=self.game.wait_state(lambda s:True)['loaded']['actor_audit']['live_enemies']
            first=next(e for e in current if e['location']<1 and e['alive'])
            assert first['enemy_id']==45,'generic enemy selector no longer points to Snow Bulborb'
            remaining=sum(e['enemy_id']==45 and e['alive'] for e in current)
            self.command('actor_defeat',location=-1)
            deadline=time.monotonic()+20
            while time.monotonic()<deadline:
                self.game.input(frames=30);after=self.playable()
                if sum(e['enemy_id']==45 and e['alive'] for e in after['loaded']['actor_audit']['live_enemies'])<remaining:break
            else:raise TimeoutError('controlled Snow Bulborb did not complete actual native death')
            assert after['physical_deliveries']==before['physical_deliveries']
            self.record('controlled-non-check-snow-bulborb-native-death',after,enemy=enemy,
                shortcut='health zero isolates carrying from combat; actual death FSM, no treasure/check/reward caller')

    def squad_at_actor(self,location,color,count):
        self.clear_snow_enemies()
        return super().squad_at_actor(location,color,count)
