"""Loaded route policy that lets real movies finish without skip/pause races."""
import time
from test_gameplay_routes import StableRoute


class SettledRoute(StableRoute):
    def playable(self,timeout=180,**identity):
        deadline=time.monotonic()+timeout
        while time.monotonic()<deadline:
            state=self.game.wait_state(lambda s:True)
            movie=state.get('movie_state',0)
            if state.get('ready') and movie==0 and not state.get('paused') and not state.get('movie_pause'):
                if all(state.get(k)==v for k,v in identity.items()):return self.record('loaded-playable',state)
            if state.get('paused') and movie==0 and state.get('ui_scene') in (10010,10013):
                self.game.press(self.driver.START,frames=8)
            elif movie or state.get('movie_pause') or state.get('ui_scene')==10018:
                # A advances actual dialogue/appraisal. Never follow it with
                # START based on a pre-A movie snapshot: the movie may already
                # have finished and START would open the ordinary pause menu.
                self.game.press(self.driver.A,frames=8)
                self.game.input(frames=20)
            else:self.game.input(frames=20)
        raise TimeoutError(f'actual scene did not settle: {identity}; last={state}')
