"""Observe a native re-lift that completes during an existing-worker recall.

Workers may finish slot attachment while the captain approaches and whistles.
Read the real same actor before each recovery input and stop obsolete walking,
aiming or whistle actions once it is actually lifted. A lift observed during
target-only throws counts as a manual recovery; earlier native re-lift uses no
manual attempt. Every other error stays strict; actual Onyon/AP and all native
equipment consumer assertions remain unchanged.
"""
import asyncio
from pathlib import Path
import test_equipment_gameplay_real_server as equipment
import test_equipment_sr_combat_setup as combat
import test_equipment_resumed_entry as resumed
from test_gameplay_real_server import make_parser


class ObservedRelift(Exception):
    def __init__(self,state,actor,manual):
        self.state=state;self.actor=actor;self.manual=manual


class ObservedRecoveryGame:
    def __init__(self,game,observe):self._game=game;self._observe=observe
    def __getattr__(self,name):return getattr(self._game,name)
    def input(self,*args,**fields):
        self._observe()
        return self._game.input(*args,**fields)
    def press(self,*args,**fields):
        self._observe()
        return self._game.press(*args,**fields)


class NaturalReliftRoute(combat.SRCombatRoute):
    def recover_existing(self,location):
        _,original,_=self.physical(location)
        game=self.game
        def observe():
            state=game.wait_state(lambda s:True)
            current=next((p for p in state['pellets'] if p['location_id']==location),None)
            if current is None:return  # Original arrival/physical handling stays strict.
            assert current['actor_id']==original['actor_id'],'recovery target identity changed'
            if current['picked']:
                raise ObservedRelift(state,current,bool(getattr(self,'_recovering_workers',False)))
        self.game=ObservedRecoveryGame(game,observe)
        try:
            try:return super().recover_existing(location)
            except AssertionError as error:
                if str(error)!='real whistle did not recruit an existing worker':raise
                observe()
                raise
        except ObservedRelift as lifted:
            self.parked_for_carry=False
            self.record('actual-native-relift-observed-during-worker-recovery',lifted.state,location=location,
                target_actor_id=lifted.actor['actor_id'],target_throw_phase=lifted.manual,boundary=__doc__)
            return lifted.manual
        finally:self.game=game


class NaturalReliftEquipment(combat.SRCombatEquipment):
    def __init__(self,session,driver,games):
        super().__init__(session,driver,games)
        self.routes={slot:NaturalReliftRoute(game,driver) for slot,game in games.items()}
        for route in self.routes.values():route.session=session


async def main(args):
    combat.SRCombatEquipment=NaturalReliftEquipment
    equipment.HELPERS.append(Path(__file__))
    await resumed.main(args)


if __name__=='__main__':
    parser=make_parser(__doc__);parser.add_argument('--resume-checkpoint',type=Path)
    asyncio.run(main(parser.parse_args()))
