"""Positive consumer attachment requires the actual native lift flag.

Pellet carry_power includes color/flower speed contributions. It cannot replace
the native total-carrier-weight check which sets isPicked; real PAD continues
until that flag is observed, followed by the separate strict Onyon requirement.
"""
import time
from test_equipment_capacity import NativeCasualties, capacity


class ActualLift:
    def attach(self, location, power, timeout=90):
        deadline = time.monotonic() + timeout
        while time.monotonic() < deadline:
            state, actor, binding = self.physical(location)
            self.record('actual-native-lift-progress', state, location=location,
                carry_speed_contribution=actor['carry_power'], picked=actor['picked'])
            if actor['picked']:
                return state, actor
            workers = [p for p in state['pikis'] if p['actor_id'] in self.main_ids]
            if capacity(workers, self.delivery_color) < binding['min_carriers']:
                raise NativeCasualties('native carrier casualties before actual lift')
            self.driver.walk_to(self.game, actor['position'], radius=65, timeout=45)
            state, actor, _ = self.physical(location)
            x, y = self.aim(state, actor)
            self.game.input(frames=75, cstick_x=x, cstick_y=y)
            # Cstick swarm direction and the whistle cursor are separate.
            # Native throwPiki targets the latter; a stale nearby corpse cursor
            # can strand two objects one literal carrier below their minima.
            state, actor, _ = self.physical(location)
            if actor['picked']:
                return state, actor
            self.driver.aim_at(self.game, actor['position'], radius=10, timeout=30)
            for _ in range(4):
                self.game.press(self.driver.A, frames=3)
        raise TimeoutError(f'actual native lift was not observed for equipment source {location}')
