"""Genuine Glint throws after observed Purple pickup, with no second warp.

Later-scene captain/sole-Purple setup is disclosed. Ordinary B recruits it;
normal held A must produce the actual Hanged4 Purple before normal release.
No health, enemy/Pikmin FSM, interaction, treasure or AP callback is assigned.
"""
import math
import time
from test_equipment_glint_press import _enemy,_released
from test_equipment_worker_recovery import xz_distance


def purple_approach(route,target):
    """Choose native ground within Purple30's actual launch 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<=xz_distance(n['position'],target)<=90]
    nodes.sort(key=lambda p:abs(xz_distance(p,target)-45))
    candidates=nodes[:8]
    for radius in (45,35,55):
        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(value) for value in ground):continue
        if target[1]-(ground[1]+10)>30:continue
        near=list(ground);near[1]+=5
        route.record('actual-purple-supported-ground-approach',state,target=target,
            position=near,ground=ground,queries=count,
            boundary='bounded native terrain queries; Purple30 plus native launch10; no enemy movement')
        return near
    raise AssertionError('no actual supported terrain within Purple throw reach near Glint')


def stage_purple(route,location):
    game,driver=route.game,route.driver
    state=route.playable();enemy=_enemy(state,location)
    near=purple_approach(route,enemy['position'])
    route.command('actor_position',actor='navi',index=0,position=near)
    game.input(frames=4);state=route.playable()
    position=list(driver.active_navi(state)['position']);position[0]+=40
    route._cleanup_reserve=True
    try:born=route.command('squad_replace',color=3,count=1,captain=0,position=position)
    finally:route._cleanup_reserve=False
    assert born['last_result']['born']==1
    purples=[p for p in born['pikis'] if p['kind']==3]
    assert len(purples)==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['actor_id']==purples[0]['actor_id'] and p['action']==0 and p['navi_id']==owner for p in state['pikis'])
    walked=game.wait_state(lambda s:driver.active_navi(s)['state']==0,15,'actual Walk before held-Purple pickup')
    driver.aim_at(game,_enemy(walked,location)['position'],radius=18,timeout=20)
    return purples[0]['actor_id']


def throw_held_purple(route,location,purple_id):
    game,driver=route.game,route.driver
    game.input(buttons=driver.A,frames=600,wait=False)
    held=None
    try:
        held=game.wait_state(lambda s:driver.active_navi(s)['state']==6 and any(
            p['actor_id']==purple_id and p['kind']==3 and p['state']==4
            and p['navi_id']==driver.active_navi(s)['actor_id'] for p in s['pikis']),4,
            'actual Purple Hanged4 and Navi ThrowWait6 while holding A')
        deadline=time.monotonic()+4;release=held;inside=False
        while time.monotonic()<deadline:
            release=game.wait_state(lambda s:True);enemy=_enemy(release,location)
            inside=(enemy['state'] in (2,3) and not release['movie_state'] and not release['paused']
                    and xz_distance(driver.active_navi(release)['cursor'],enemy['position'])<50)
            if inside:break
            time.sleep(.05)
        return {'held':held,'release_before':release,'release_in_press_range':inside}
    except TimeoutError as error:
        return {'held':None,'release_before':game.wait_state(lambda s:True),
                'release_in_press_range':False,'pickup_failure':str(error).split('; log ')[0][:300]}
    finally:
        # This is the ordinary A-up throw. Always observe its actual outcome,
        # including an out-of-range or timed-out pickup attempt.
        game.input(frames=6)


def release_glint_held(route,location=65,timeout=150):
    initial=route.playable();holder=_enemy(initial,location)
    assert holder['enemy_id']==10 and holder['health']>0 and not _released(initial,location)
    deadline=time.monotonic()+timeout;throws=[];samples=[];pressed=False
    for attempt in range(8):
        if time.monotonic()>=deadline:break
        purple_id=stage_purple(route,location)
        evidence=throw_held_purple(route,location,purple_id)
        throws.append(dict(evidence,attempt=attempt+1,purple_id=purple_id))
        observe_until=min(deadline,time.monotonic()+5)
        while time.monotonic()<observe_until:
            state=route.game.wait_state(lambda s:True);enemy=_enemy(state,location)
            pressed |= 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 evidence['held'] is not None,'actual Purple pickup must precede the credited throw'
                assert pressed,'actual native KOGANE Press4 must be observed before release'
                _,actor,binding=route.physical(location,15)
                assert binding['collision_model_matches'] and binding['location']==location
                result={'location':location,'holder_before':holder,'throws':throws,'samples':samples,
                    'released_state':state,'actor':actor,'binding':binding,'observed_press_state':True,
                    'boundary':__doc__,'source_path':'actual held Purple A-up -> native landing/quake -> Kogane Press4 -> source-traced KEYEVENT3 -> original treasure'}
                route.record('actual-held-purple-glint-release',state,evidence=result)
                return result
            route.game.input(frames=3)
    raise TimeoutError(f'actual held-Purple throws did not release Glint {location}; attempts={len(throws)}, press_seen={pressed}')
