"""Equipment consumer scope with actual surviving squads and retained AP checkpoints."""
import asyncio
import json
import time
from pathlib import Path
import test_equipment_gameplay_real_server as equipment
from test_gameplay_carriers import ConsumerRoute
from test_gameplay_real_server import make_parser,run


class NearConsumerRoute(ConsumerRoute):
    def clear_hob_geysers(self,location):
        if location!=51:return
        before=self.playable()
        if (before['course'],before['cave'],before['floor'])!=(1,1717514289,2):return
        checks={s:set(self.session.ctx.location_checks[0,s]) for s in (1,2)}
        receipts={s:self.session.native_journal(s)['receipts'] for s in (1,2)}
        cleaned=[]
        for _ in range(24):
            state=self.playable()
            generic=[e for e in state['loaded']['actor_audit']['live_enemies'] if e['location']<1 and e['alive']]
            if not generic or generic[0]['enemy_id']!=20:break
            selected=generic[0]
            position=list(selected['position']);position[0]-=35;position[1]+=5
            self.command('actor_position',actor='navi',index=0,position=position)
            self.game.input(frames=20);state=self.playable()
            first=next(e for e in state['loaded']['actor_audit']['live_enemies'] if e['location']<1 and e['alive'])
            assert first['enemy_id']==20 and self.driver.distance(first['position'],selected['position'])<1, 'generic selector changed Hiba instance'
            self.command('actor_defeat',location=-1)
            deadline=time.monotonic()+30
            while time.monotonic()<deadline:
                self.game.input(frames=30);after=self.playable()
                matching=[e for e in after['loaded']['actor_audit']['live_enemies']
                    if e['enemy_id']==20 and self.driver.distance(e['position'],selected['position'])<1]
                if not any(e['alive'] for e in matching):break
            else:raise TimeoutError('controlled Hiba health zero did not complete native FSM death')
            assert after['physical_deliveries']==before['physical_deliveries']
            cleaned.append({'selected':selected,'after':matching,'physical_deliveries':after['physical_deliveries']})
            self.record('controlled-hiba-native-death',after,selected=selected,
                shortcut='exact stationary enemy20 at authored position; hazard combat bypassed before equipment carry')
        else:raise AssertionError('bounded targeted Hiba cleanup exceeded')
        assert checks=={s:set(self.session.ctx.location_checks[0,s]) for s in (1,2)}
        assert receipts=={s:self.session.native_journal(s)['receipts'] for s in (1,2)}
        self.session.event('equipment-targeted-hiba-native-cleanup',location=location,cleared=cleaned,
            ap_checks_unchanged={str(s):sorted(v) for s,v in checks.items()},native_receipts_unchanged=receipts,
            shortcut='test health-zero stimulus only for exact stationary Hiba20; native death FSM, no combat claim')

    def squad_at_actor(self,location,color,count):
        self.clear_hob_geysers(location)
        self.clear_snow_enemies()
        _,actor,binding=self.physical(location)
        position=list(actor['position']);position[0]-=25
        position=self.command('ground_query',position=position)['last_result']['position'];position[1]+=5
        self.command('actor_position',actor='navi',index=0,position=position)
        self.game.input(frames=20);self.playable()
        born=self.command('squad_replace',color=color,count=count,captain=0,position=position)
        assert born['last_result']['born']==count
        strength=10 if color==3 else 1
        for _ in range(5):
            state=self.playable();live=state['pikis']
            assert live and len(live)*strength>=binding['min_carriers']
            center=[sum(p['position'][i] for p in live)/len(live) for i in range(3)]
            # Captain setup is already disclosed; keep its initial test position
            # beside the actual squad rather than claim normal combat/travel.
            captain=self.driver.active_navi(state)
            if self.driver.distance(captain['position'],center)>65:
                near=self.command('ground_query',position=center)['last_result']['position'];near[1]+=5
                self.command('actor_position',actor='navi',index=0,position=near)
                self.game.input(frames=12);self.playable()
            self.driver.aim_at(self.game,center,radius=20)
            self.game.input(buttons=self.driver.B,frames=120);self.game.input(frames=8)
            state=self.playable();owner=self.driver.active_navi(state)['actor_id']
            if all(p['kind']==color and p['action']==0 and p['navi_id']==owner for p in state['pikis']):break
        else:raise AssertionError('surviving equipment squad failed actual Formation recruitment')
        assert len(state['pikis'])*strength>=binding['min_carriers']
        self.record('equipment-actual-surviving-formation',state,requested=count,surviving=len(state['pikis']),
            shortcut='captain/squad prepared beside authored treasure; ordinary approach and combat not exercised')
        return actor,binding


class SurvivingEquipment(equipment.Equipment):
    def __init__(self,session,driver,games):
        super().__init__(session,driver,games)
        self.routes={s:NearConsumerRoute(game,driver) for s,game in games.items()}
        for route in self.routes.values():route.session=session


async def main(args):
    equipment.Equipment=SurvivingEquipment
    equipment.HELPERS.extend((Path(__file__).resolve(),Path(__file__).with_name('test_gameplay_carriers.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',encoding='utf8')


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