"""Equipment continuation measuring a fully charged actual native whistle."""
import asyncio
import json
import time
from pathlib import Path
import test_equipment_gameplay_real_server as equipment
from test_equipment_practical import PracticalEquipment,EXTRA
from test_gameplay_real_server import make_parser,run


class ChargedEquipment(PracticalEquipment):
    async def punch(self):
        game=self.games[2]
        await self.empty_overworld(2)
        before=await asyncio.to_thread(self.routes[2].playable)
        equipped=bool(before['equipment'] & 1)
        def stream():
            pulses=[];samples=[]
            for spacing in (.065,.085,.115):
                started=time.monotonic();observed=-1
                for index in range(100 if equipped else 30):
                    game.sequence+=1
                    request={'id':game.sequence,'op':'input','buttons':self.driver.A,'frames':2,
                        'stick_x':0,'stick_y':0,'cstick_x':0,'cstick_y':0}
                    temp=game.control_dir/'punch-input.tmp';temp.write_text(json.dumps(request))
                    deadline=time.monotonic()+2
                    while True:
                        try:temp.replace(game.control_dir/'control.json');break
                        except PermissionError:
                            if time.monotonic()>deadline:raise
                            time.sleep(.002)
                    pulses.append({'seconds':time.monotonic()-started,'spacing':spacing,'request':request})
                    # This observation must remain nonblocking: waiting for
                    # 100ms publications would span an entire native punch.
                    # A missing transient snapshot gives no credit; the final
                    # ordinary neutral command must be explicitly ACKed.
                    state=game.state()
                    if state and state['response_id']!=observed:
                        observed=state['response_id']
                        samples.append({k:state[k] for k in ('response_id','retrace','equipment')} |
                            {'captains':state['effects']['captains']})
                        if equipped and max(c['punch_combo_max_observed'] for c in state['effects']['captains'])>=2:break
                    time.sleep(max(0,started+(index+1)*spacing-time.monotonic()))
                final=game.input(frames=30)
                assert final['response_id']==game.sequence and final['input_remaining']==0
                value=max(c['punch_combo_max_observed'] for c in final['effects']['captains'])
                if not equipped or value>=2:return value,final,pulses,samples
            return value,final,pulses,samples
        value,after,pulses,samples=await asyncio.to_thread(stream)
        passed=value>=2 if equipped else value==0
        self.session.event('actual-streamed-punch-consumer',value=value,passed=passed,pulses=pulses,
            samples=samples,final_neutral_ack=after,
            boundary='standard atomic PAD A2 requests; actual native animation END counter; no FSM/event setters')
        assert passed,'actual Brute punch combo failed; see streamed-punch-consumer event'
        return value,after

    async def sprouts(self):
        if 'sprouts' not in self.session.consumer_state['baselines']:
            # A fresh negative control still proves real number-pellet
            # reproduction. Reuse applies only to later positive controls.
            return await super().sprouts()
        route=self.routes[2];game=self.games[2]
        state=await asyncio.to_thread(route.scene,0)
        if not state['sprouts']:return await super().sprouts()
        # The original negative control already produced real planted seeds.
        # Their actual B-uprooting is the consumer; a second reproduction is
        # unnecessary, and no seeds or reward effects are injected here.
        center=[sum(p['position'][i] for p in state['sprouts'])/len(state['sprouts']) for i in range(3)]
        position=list(center);position[0]-=45
        position=(await asyncio.to_thread(route.command,'ground_query',position=position))['last_result']['position'];position[1]+=5
        await asyncio.to_thread(route.command,'actor_position',actor='navi',index=0,position=position)
        await asyncio.to_thread(game.input,frames=20);await asyncio.to_thread(route.playable)
        await asyncio.to_thread(self.driver.aim_at,game,center,radius=15)
        before=await asyncio.to_thread(game.wait_state,lambda s:True)
        assert before['sprouts']
        self.session.event('equipment-existing-native-sprouts',state=before,
            boundary='retained actual Onion reproduction; captain setup only, no seed or effect setter')
        return before,center

    async def controller_effect(self,slot,kind):
        if kind!='whistle':return await super().controller_effect(slot,kind)
        game=self.games[slot]
        before=await asyncio.to_thread(self.routes[slot].playable)
        amplified=bool(before['equipment'] & (1<<(503-501)))
        await asyncio.to_thread(game.input,buttons=self.driver.B,frames=300,wait=False)
        whistle_sequence=game.sequence
        deadline=time.monotonic()+120;samples=[];state=None;value=-1
        while time.monotonic()<deadline:
            current=await asyncio.to_thread(game.wait_state,lambda s:True)
            radius=max(c['whistle_radius'] for c in current['effects']['captains'])
            samples.append({k:current[k] for k in ('response_id','retrace','input_remaining')} |
                {'captains':current['effects']['captains']})
            if radius>value:value=radius;state=current
            if current['input_remaining']==0:
                assert current['response_id']==whistle_sequence,'held-whistle completion requires its own ACK'
                break
            await asyncio.sleep(.05)
        else:raise TimeoutError('actual held-whistle PAD interval did not complete')
        if amplified:assert value>max(c['normal_whistle'] for c in state['effects']['captains'])+20
        else:assert value>max(c['normal_whistle'] for c in state['effects']['captains'])*.8
        await asyncio.to_thread(game.input,frames=20)
        self.session.event('actual-controller-equipment-consumer',slot=slot,kind=kind,value=value,state=state,
            samples=samples,completed_interval=current,
            boundary='maximum actual radius over complete acknowledged B300 interval; native charge ends before theoretical maximum')
        return value,state


async def main(args):
    equipment.Equipment=ChargedEquipment
    equipment.HELPERS.extend(Path(__file__).with_name(n) for n in EXTRA)
    equipment.HELPERS.extend(Path(__file__).with_name(n) for n in
        ('test_equipment_practical.py','test_gameplay_arrival_policy.py','test_equipment_charged.py'))
    report=await run(args,acceptance=equipment.accept,scope_gates=(),acceptance_kind='loaded_scene',boundary=equipment.__doc__)
    event=next(e for e in report['events'] if e['label']=='equipment-consumers-scope-passed')
    report['subgates']={'equipment_consumers':{k:event[k] for k in ('passed','consumer_item_ids','evidence','boundary','helper_sha256')}}
    report['broad_progression_gate_claimed']=False
    (args.output/'report.json').write_text(json.dumps(report,indent=2)+'\n')


if __name__=='__main__':
    parser=make_parser(__doc__);parser.add_argument('--resume-checkpoint',type=Path)
    asyncio.run(main(parser.parse_args()))
