"""Controlled later-scene Yellow crew; real PAD combat stops native bomb producers.

No enemy, health, animation, treasure, check or reward setter is used. At most40
ordinary Yellow workers fight at the actual producer, spatially away from the
treasure; strict unchanged-target/AP checks remain the isolation boundary.
The captain and crew are disclosed test setup; throws, latch/knockdown, damage and death are
ordinary production gameplay. This is not a normal campaign/combat claim.
"""
import math
import time


def enemies(state):
    return state['loaded']['actor_audit']['live_enemies']


def living_index(state):
    assert len(state['navi']) == len(state['effects']['captains'])
    active = next(i for i, n in enumerate(state['navi']) if n['active'])
    row = state['effects']['captains'][active]
    assert row['health'] > 0
    return row['index']


def supported_approach(route, target):
    """Read native terrain; reject pit staging beyond Yellow's115 throw height."""
    state = route.playable()
    nodes = [n['position'] for n in state.get('loaded', {}).get('routes', [])
             if not n['closed'] and not n['water']
             and 25 <= math.dist((n['position'][0], n['position'][2]), (target[0], target[2])) <= 90]
    nodes.sort(key=lambda p: abs(math.dist((p[0], p[2]), (target[0], target[2])) - 55))
    candidates = nodes[:8]
    for radius in (55, 75, 35):
        candidates.extend([target[0] + radius * math.cos(i * math.pi / 4), target[1],
                           target[2] + radius * math.sin(i * math.pi / 4)] for i in range(8))
    for count, candidate in enumerate(candidates, 1):
        ground = route.command('ground_query', position=candidate)['last_result']['position']
        if not all(math.isfinite(x) for x in ground):
            continue
        # Piki::getThrowHeight Yellow115; Navi::throwPiki starts10 above
        # captain elevation. Actual GetMinY rejects the old -128 pit approach.
        height = target[1] - (ground[1] + 10)
        if height > 115:
            continue
        near = list(ground); near[1] += 5
        route.record('actual-terrain-supported-combat-approach', state,
            target=target, position=near, ground=ground, height_above_launch=height, queries=count,
            boundary='bounded native route/radial ground queries; source Yellow115 throw reach, no enemy movement')
        return near
    raise AssertionError('no actual supported terrain within Yellow throw range near producer/Free crew')


def recruit_free_crew(route, state, crew_ids, color=None):
    """Recall only existing Free workers, without interrupting actual work.

    Captain positioning is disclosed fixture setup. B recruitment and native
    ownership are ordinary gameplay. This function never births workers or
    changes a caller's casualty/retry budget.
    """
    game, driver = route.game, route.driver
    for attempt in range(3):
        live = [p for p in state['pikis'] if p['actor_id'] in crew_ids
                and (p['kind'] == color if color is not None else p['kind'] != 0)]
        owner = driver.active_navi(state)['actor_id']
        if any(p['action'] in (4, 5) for p in live):
            return state  # Never whistle off a real transporter/attacker.
        if any(p['action'] == 0 and p['navi_id'] == owner for p in live):
            return state
        free = [p for p in live if p['action'] == 1 and p['state'] == 0]
        if not free:
            return state
        clusters = [[p for p in free if driver.distance(p['position'], seed['position']) < 100]
                    for seed in free]
        cluster = max(clusters, key=len)
        center = [sum(p['position'][i] for p in cluster) / len(cluster) for i in range(3)]
        near = supported_approach(route, center)
        fresh = route.playable()
        if any(p['actor_id'] in crew_ids and p['action'] in (4, 5) for p in fresh['pikis']):
            return fresh
        route.command('actor_position', actor='navi', index=living_index(fresh), position=near)
        driver.aim_at(game, center, radius=20, timeout=30)
        fresh = route.playable()
        if any(p['actor_id'] in crew_ids and p['action'] in (4, 5) for p in fresh['pikis']):
            return fresh
        game.input(buttons=driver.B, frames=90); game.input(frames=8)
        state = route.playable()
        owner = driver.active_navi(state)['actor_id']
        recalled = [p for p in state['pikis'] if p['actor_id'] in crew_ids and p['action'] == 0
                    and p['navi_id'] == owner and (p['kind'] == color if color is not None else p['kind'] != 0)]
        route.record('actual-existing-combat-crew-recruitment', state,
            attempt=attempt + 1, selected_ids=[p['actor_id'] for p in cluster],
            recalled_ids=[p['actor_id'] for p in recalled],
            boundary='existing Free workers, surviving captain fixture position then actual B; no birth, health or retry reset')
        if recalled:
            return state
    raise TimeoutError('existing Free combat crew did not enter actual surviving-captain Formation')


def clear_dirigibugs(route, location=142, timeout=180, crew_count=40):
    game, driver = route.game, route.driver
    assert 1 <= crew_count <= 40, 'bounded actual combat fixture crew'
    initial, target, binding = route.physical(location)
    producers = [e for e in enemies(initial) if e['enemy_id'] == 58 and e['alive'] and e['health'] > 0]
    assert len(producers) <= 4
    evidence = []
    for ordinal in range(len(producers)):
        state = route.playable()
        remaining = [e for e in enemies(state) if e['enemy_id'] == 58 and e['alive'] and e['health'] > 0]
        if not remaining:
            # A real intervening bomb may have dealt the last damage. Do not
            # credit health0 alone: require the native death state to finish.
            deadline = time.monotonic() + timeout
            while time.monotonic() < deadline:
                state = route.playable()
                settled = [e for e in enemies(state) if e['enemy_id'] == 58]
                if settled and all(e['state'] == 0 and e['health'] <= 0 for e in settled):
                    evidence.append({'producer_deaths_observed_before_staging': settled,
                        'boundary': 'ordinary native intervening damage; all remaining producers observed health0/nativeDead0, no health setter'})
                    break
                game.input(frames=30)
            else:
                raise TimeoutError('native producer health0 had not completed its actual death state')
            break
        # In this authored scene each producer stays in its own distant
        # territory. Select the nearest observed one; after death it is never
        # selected again. No target/dropLocation0 selector is invoked.
        captain = driver.active_navi(state)
        before = min(remaining, key=lambda e: driver.distance(e['position'], captain['position']))
        current = before
        ground = route.command('ground_query', position=current['position'])['last_result']['position']
        if current['position'][1] - ground[1] > 200:
            # Native $1 drop groups are deliberately atY300 until a genuine
            # Piki/Navi arrives. Activate one actual Free Piki first; never
            # pretend a115-height throw should reach the dormant marker.
            assert route.free_birth(2, ground)['last_result']['born'] == 1
            deadline = time.monotonic() + 30
            while time.monotonic() < deadline:
                game.input(frames=30); state = route.playable()
                current = min([e for e in enemies(state) if e['enemy_id'] == 58],
                    key=lambda e: driver.distance(e['position'], current['position']))
                if current['position'][1] - ground[1] < 150:
                    route.record('actual-free-pikmin-dirigibug-appearance', state, producer=current,
                        boundary='one actual Free Yellow activates original proximity-drop lifecycle; no enemy position/FSM setter')
                    break
            else:
                raise TimeoutError('actual Piki bait did not activate native producer appearance')
        def stage_crew(enemy):
            state = route.playable()
            near = supported_approach(route, enemy['position'])
            state = route.playable()
            index = living_index(state)
            route.command('actor_position', actor='navi', index=index, position=near)
            born = route._command_with_movie_guard('squad_replace',
                dict(color=2, count=crew_count, captain=index, position=near), raw=True)
            assert born['last_result']['born'] == crew_count
            ids = {p['actor_id'] for p in born['pikis'] if p['kind'] == 2}
            pod = next(o for o in born['onyons'] if o['type'] == 3)
            reserve = route.command('ground_query', position=pod['position'])['last_result']['position']
            assert route.free_birth(0, reserve)['last_result']['born'] == 1
            driver.aim_at(game, near, radius=20, timeout=30)
            game.input(buttons=driver.B, frames=90); game.input(frames=8)
            return ids
        crew = stage_crew(current)
        attempts = 1; casualties = []
        samples = []; deadline = time.monotonic() + timeout; damage_seen = False; fall_seen = False
        while time.monotonic() < deadline:
            state = route.playable()
            choices = [e for e in enemies(state) if e['enemy_id'] == 58]
            # Producer movement is continuous, so nearest-last-position is
            # used only within this deliberately isolated territory.
            assert choices, 'the observed producer must remain in the native readback through death'
            current = min(choices, key=lambda e: driver.distance(e['position'], current['position']))
            damage_seen |= current['health'] < before['health']
            fall_seen |= current['state'] == 8
            samples.append({'retrace': state['retrace'], 'enemy': current,
                'captains': state['effects']['captains'],
                'crew': [p for p in state['pikis'] if p['actor_id'] in crew]})
            if current['state'] == 0 and current['health'] <= 0:
                assert damage_seen, 'ordinary actual attacks must reduce producer health'
                _, same, _ = route.physical(location)
                assert same['actor_id'] == target['actor_id']
                row = {'producer_before': before, 'producer_after': current, 'samples': samples,
                    'knockdown_observed': fall_seen, 'actual_damage_observed': damage_seen,
                    'target_actor_id': target['actor_id'], 'crew_literal_capacity': crew_count,
                    'target_minimum': binding['min_carriers'], 'crew_attempts': attempts, 'casualty_restage': casualties,
                    'boundary': __doc__}
                evidence.append(row)
                route.record('actual-yellow-dirigibug-combat-death', state, evidence=row)
                break
            live = [p for p in state['pikis'] if p['actor_id'] in crew and p['kind'] == 2]
            if not live:
                assert attempts < 3, 'three actual combat crews died; do not infer producer cleanup'
                # Preserve actual producer damage. Leave its released bombs
                # to their real fuses while captain/reserve stay at the pod.
                pod = next(o for o in state['onyons'] if o['type'] == 3)
                safe = route.command('ground_query', position=pod['position'])['last_result']['position']; safe[1] += 5
                route.command('actor_position', actor='navi', index=living_index(state), position=safe)
                game.input(frames=360)
                settled = route.playable()
                casualties.append({'attempt': attempts, 'state_before': state, 'after_native_fuse_wait': settled,
                    'boundary': 'only complete actual Yellow crew loss permits restage; actual producer damage and bombs unchanged'})
                route.record('actual-dirigibug-crew-casualty-before-restage', settled, evidence=casualties[-1])
                choices = [e for e in enemies(settled) if e['enemy_id'] == 58]
                current = min(choices, key=lambda e: driver.distance(e['position'], current['position']))
                crew = stage_crew(current); attempts += 1
                continue
            state = recruit_free_crew(route, state, crew, color=2)
            # The cursor is on terrain, not at the flying enemy's Y. Actual
            # Yellow throw height reaches it through the normal ballistic arc.
            aim = route.command('ground_query', position=current['position'])['last_result']['position']
            # A blast may change the active captain during the read-only
            # query. Never use the preceding captain snapshot for aim setup.
            state = route.playable()
            cap = driver.active_navi(state)
            if driver.distance(cap['position'], aim) > 90:
                near = supported_approach(route, current['position'])
                state = route.playable()
                route.command('actor_position', actor='navi', index=living_index(state), position=near)
                game.input(frames=8)
            driver.aim_at(game, aim, radius=15, timeout=30)
            for _ in range(5): game.press(driver.A, frames=3)
            game.input(frames=30)
        else:
            raise TimeoutError('ordinary Yellow attacks did not complete actual Dirigibug death')
    final = route.playable()
    assert all(e['state'] == 0 and e['health'] <= 0 for e in enemies(final) if e['enemy_id'] == 58), \
        'all actual native producer death states must be observed, not merely health0'
    return {'producers': evidence, 'state': final, 'boundary': __doc__}
