"""Release a Glint Beetle's original treasure through genuine Purple PAD throws.

Captain/Pikmin positioning is explicit fixture setup. No health, enemy FSM,
press/quake, animation-event, treasure, check or reward callback is assigned.
"""
import math
import time
from test_loaded_gameplay_real_server import LoadedRoute


def _enemy(state, location):
    return next(e for e in state['loaded']['actor_audit']['enemies'] if e['location']==location)


def _released(state, location):
    audit=state['loaded']['actor_audit']
    actors=[a for a in audit['actors'] if a['location']==location and a['alive']
        and not a['captured_now'] and not (a['pool_flags']&0x65)]
    return bool(actors and any(p['location_id']==location for p in state['pellets']))


def release_glint(route, location=65, timeout=150):
    game,driver=route.game,route.driver
    initial=route.playable()
    holder=_enemy(initial,location)
    assert holder['enemy_id']==10,'this actuator is only for original Wealthy/Glint Beetles'
    assert holder['health']>0,'Glint actuator must run before any health-zero shortcut'
    assert not _released(initial,location),'original Glint treasure was already loose'
    samples=[];throws=[];pressed=False;deadline=time.monotonic()+timeout
    for attempt in range(8):
        if time.monotonic()>=deadline:break
        state=route.playable();enemy=_enemy(state,location)
        target=list(enemy['position'])
        near=list(target);near[0]-=45
        near=route.command('ground_query',position=near)['last_result']['position'];near[1]+=5
        route.command('actor_position',actor='navi',index=0,position=near)
        # Native one-Piki birth starts at origin.x-40; compensate only that
        # documented setup grid, without moving the enemy or its treasure.
        origin=list(near);origin[0]+=40
        # RecruitingRoute.command would whistle every pre-existing free
        # actor, including the distant inherited cave squad. Birth only this
        # declared actor; its actual whistle recruitment is checked below.
        born=route.free_birth(3,near) if hasattr(route,'free_birth') else LoadedRoute.command(
            route,'squad_setup',color=3,count=1,captain=0,position=origin)
        assert born['last_result']['born']==1
        game.input(buttons=driver.B,frames=45);game.input(frames=6)
        state=route.playable();owner=driver.active_navi(state)['actor_id']
        assert any(p['kind']==3 and p['navi_id']==owner and p['action']==0 for p in state['pikis']),\
            'actual Purple Formation recruitment required before throwing'
        target=list(_enemy(state,location)['position'])
        # The target may move. Approach by disclosed captain setup, then aim
        # the ordinary controller cursor; the native Purple landing/quake
        # (default radius60) provides the actual press interaction.
        near=list(target);near[0]-=45
        near=route.command('ground_query',position=near)['last_result']['position'];near[1]+=5
        route.command('actor_position',actor='navi',index=0,position=near)
        game.input(frames=4)
        driver.aim_at(game,target,radius=18,timeout=min(20,max(1,deadline-time.monotonic())))
        before=game.wait_state(lambda s:True)
        game.press(driver.A,frames=6)
        throws.append({'attempt':attempt+1,'before_retrace':before['retrace'],
            'enemy_before':_enemy(before,location),'captain':driver.active_navi(before),
            'boundary':'normal A press/release throws actual recruited Purple; no direct interaction call'})
        observe_until=min(deadline,time.monotonic()+5)
        while time.monotonic()<observe_until:
            state=game.wait_state(lambda s:True)
            enemy=_enemy(state,location)
            pressed=pressed or enemy['state']==4
            samples.append({'retrace':state['retrace'],'enemy':enemy,
                'purples':[p for p in state['pikis'] if p['kind']==3],
                'released':_released(state,location)})
            if _released(state,location):
                assert pressed,'native KOGANE_Press must be observed before the treasure release'
                _,actor,binding=route.physical(location,timeout=15)
                assert binding['collision_model_matches'] and binding['location']==location
                evidence={'location':location,'holder_before':holder,'throws':throws,'samples':samples,
                    'released_state':state,'actor':actor,'binding':binding,'observed_press_state':True,
                    'boundary':__doc__,'source_path':'Kogane Press KEYEVENT_3 -> Wealthy.createItem -> createTreasureItem; animation key is source-traced, not an injected or separately observed event'}
                route.record('actual-glint-purple-press-treasure-release',state,evidence=evidence)
                return evidence
            game.input(frames=3)
    raise TimeoutError(f'actual Purple throws did not release Glint treasure {location}; throws={len(throws)} press_seen={pressed}')
