"""Render real frames between repeated opt-in squad mutations.

This is a test-fixture lifetime regression, not carrying, AP delivery, card-save
or campaign evidence. Actual pooled Piki models are rebuilt only after draw
buffers clear and before the next update enters model packets.
"""
import asyncio
import json
import time
from pathlib import Path
from test_gameplay_real_server import make_parser,run
from test_gameplay_settled_route import SettledRoute
from test_real_server import sha

HELPERS=[Path(__file__).with_name(name) for name in ('test_gameplay_settled_route.py',
    'test_gameplay_routes.py','test_loaded_gameplay_recruitment.py')]

def error_snapshot(game):
    deadline=time.monotonic()+5
    while time.monotonic()<deadline:
        state=game.state()
        if state and state.get('response_id')==game.sequence and state.get('error'):return state
        time.sleep(.05)
    raise TimeoutError('expected acknowledged native command error snapshot')

async def accept(session,driver):
    pins={str(path.resolve()):sha(path) for path in HELPERS}
    configured=session.runs[1]
    game=driver.GameplayClient(session.args.native,session.args.assets,configured['profile'],
        configured['directory']/'phase-control',configured['save'],session.output/'phase-native.log')
    session.register_cleanup(lambda:asyncio.to_thread(game.shutdown))
    await asyncio.to_thread(game.start)
    boot=await asyncio.to_thread(driver.boot_day1,game,timeout=300)
    route=SettledRoute(game,driver)
    initial=await asyncio.to_thread(route.playable)
    assert len(initial['pikis'])==5 and all(p['kind']==1 for p in initial['pikis'])
    center=[sum(p['position'][i] for p in initial['pikis'])/5 for i in range(3)]
    await asyncio.to_thread(driver.walk_to,game,center,radius=50,timeout=45)
    await asyncio.to_thread(driver.aim_at,game,center,radius=15)
    await asyncio.to_thread(game.input,buttons=driver.B,frames=120)
    movie=await asyncio.to_thread(game.wait_state,lambda s:s.get('movie_state',0)>0,15,'genuine first Red movie')
    try:
        await asyncio.to_thread(game.command,'squad_replace',color=1,count=2,captain=0)
        raise AssertionError('movie-time model replacement unexpectedly executed')
    except RuntimeError as error:
        assert 'test mutation busy:' in str(error)
        busy=await asyncio.to_thread(error_snapshot,game)
        assert busy['test_dispatch']['last_busy_id']==game.sequence
        assert busy['test_dispatch']['last_busy_movie_state']>0
        assert not busy['test_dispatch']['pending'] and len(busy['pikis'])==5
        assert busy['test_dispatch']['mutation_count']==0
    recovered=await asyncio.to_thread(game.input,buttons=driver.A,frames=8)
    assert recovered['response_id']>busy['response_id'] and recovered['error'] is None
    await asyncio.to_thread(game.input,frames=8)
    await asyncio.to_thread(route.playable)
    # Trigger an actual treasure-discovery movie through its normal proximity
    # caller. Only the captain is positioned; no movie/story flag is assigned.
    current=await asyncio.to_thread(game.wait_state,lambda s:True)
    treasure=next(p for p in current['pellets'] if p['location_id']==1)
    position=list(treasure['position']);position[2]-=30;position[1]+=10
    await asyncio.to_thread(route.command,'actor_position',actor='navi',index=0,position=position)
    actual_movie=await asyncio.to_thread(game.wait_state,
        lambda s:s.get('movie')=='g04_find_treasure' and s.get('movie_state')==5
            and not s.get('paused') and not s.get('movie_pause'),45,
        'real treasure-discovery movie active without combat pause')
    enemy=next(e for e in actual_movie['loaded']['actor_audit']['enemies'] if e['alive'] and e['health']>0)
    health=await asyncio.to_thread(game.command,'actor_defeat',location=enemy['location'])
    assert health['test_dispatch']['last_mutation_op']=='actor_defeat'
    assert health['test_dispatch']['last_mutation_movie_state']==5
    assert health['test_dispatch']['queued_draw_generation']!=health['test_dispatch']['executed_draw_generation']
    session.event('pending-real-movie-busy-and-health-dispatch',movie=movie,busy=busy,
        new_input=recovered,health_movie=actual_movie,health_ack=health,enemy=enemy,
        boundary='actual first Red movie rejects queued model mutation; new serial input recovers; '
            'actual proximity-triggered treasure movie permits health-only command, no combat/death claim')
    await asyncio.to_thread(route.playable)
    await asyncio.to_thread(route.command,'actor_position',actor='navi',index=0,position=[-300,10,2950])
    cases=[];last_id=0;last_count=0
    for index in range(25):
        color=index%5
        count=(1,17,5,32,9)[index%5]
        state=await asyncio.to_thread(route.command,'squad_replace',color=color,count=count,captain=0)
        dispatch=state['test_dispatch']
        assert dispatch['last_mutation_op']=='squad_replace'
        assert dispatch['last_mutation_id']==state['response_id']>last_id
        assert dispatch['mutation_count']>last_count
        assert dispatch['phase']=='after_draw_before_update'
        assert dispatch['queued_draw_generation']!=dispatch['executed_draw_generation']
        assert state['last_result']['born']==count and len(state['pikis'])==count
        assert all(p['kind']==color for p in state['pikis'])
        rendered=await asyncio.to_thread(game.input,frames=12)
        assert rendered['retrace']>state['retrace']
        assert rendered['test_dispatch']['draw_generation']>dispatch['executed_draw_generation']
        assert rendered['test_dispatch']['mutation_count']==dispatch['mutation_count']
        assert rendered['game_state']==3 and rendered['error'] is None
        cases.append({'op':'squad_replace','index':index,'count':count,'color':color,'dispatch':dispatch,
            'ack_retrace':state['retrace'],'rendered_retrace':rendered['retrace'],
            'rendered_generation':rendered['test_dispatch']['draw_generation']})
        last_id,last_count=dispatch['last_mutation_id'],dispatch['mutation_count']
    additions=[]
    for color in range(5):
        expected=9+2*(color+1)
        state=await asyncio.to_thread(game.command,'squad_setup',color=color,count=2,captain=0)
        dispatch=state['test_dispatch']
        assert dispatch['last_mutation_op']=='squad_setup'
        assert dispatch['last_mutation_id']==state['response_id']>last_id
        assert dispatch['mutation_count']==last_count+1
        assert dispatch['queued_draw_generation']!=dispatch['executed_draw_generation']
        assert state['last_result']['born']==2 and len(state['pikis'])==expected
        rendered=await asyncio.to_thread(game.input,frames=12)
        assert rendered['retrace']>state['retrace']
        assert rendered['test_dispatch']['draw_generation']>dispatch['executed_draw_generation']
        additions.append({'color':color,'expected':expected,'dispatch':dispatch,
            'rendered_retrace':rendered['retrace'],'rendered_generation':rendered['test_dispatch']['draw_generation']})
        last_id,last_count=dispatch['last_mutation_id'],dispatch['mutation_count']
    try:
        await asyncio.to_thread(game.command,'squad_replace',color=1,count=0,captain=0)
        raise AssertionError('invalid mutation unexpectedly accepted')
    except RuntimeError:
        invalid=await asyncio.to_thread(error_snapshot,game)
        assert invalid['response_id']==game.sequence
        assert 'invalid squad setup' in invalid['error']
        assert invalid['test_dispatch']['mutation_count']==last_count
        assert len(invalid['pikis'])==19
    assert all(sha(Path(path))==digest for path,digest in pins.items())
    session.event('safe-mutation-phase-regression-passed',passed=True,cases=cases,additions=additions,invalid=invalid,
        boot=boot,helper_sha256=pins,boundary=__doc__,
        shortcuts=['normal title/new-game and genuine first Red tutorial',
            'captain positioned in test staging area; real pooled squads repeatedly replaced',
            'no AP client connection, reward/check callback, card save or campaign claim'])

if __name__=='__main__':
    asyncio.run(run(make_parser(__doc__).parse_args(),acceptance=accept,scope_gates=(),
        acceptance_kind='fixture_render_lifetime',boundary=__doc__))
