"""Original equipment consumers with factual burial metadata and real native arrival checks."""
import asyncio
import json
import math
from pathlib import Path
import test_equipment_gameplay_real_server as equipment
from test_gameplay_digging_cases import DiggingRoute,prepare_digging_squad,EXTRA
from test_gameplay_real_server import make_parser,run
from test_gameplay_arrival_policy import AppraisalArrival


def carrier_color(required,binding,target_name,buried_names):
    listed_burial=not binding['remote'] and target_name in buried_names
    color=0 if 'blue' in required else 4 if listed_burial or 'white' in required else 2 if 'yellow' in required else 1
    return 3 if binding['min_carriers']>100 else color


class TargetLeftActorList(RuntimeError):
    pass


class PracticalRoute(AppraisalArrival,DiggingRoute):
    def clear_hob_geysers(self,location):
        # Reds can acquire partially visible Brute Knuckles among native fire.
        # Unrelated hazards are preserved; no all-geyser cleanup is required.
        pass

    def squad_at_actor(self,location,color,count):
        _,actor,binding=self.physical(location)
        if color==4 and binding['depth_max']>0:
            return prepare_digging_squad(self,location,color,count)
        self.clear_snow_enemies()
        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)]
            if self.driver.distance(self.driver.active_navi(state)['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']
            targets=[p for p in state['pellets'] if p['location_id']==location]
            if not targets:raise TargetLeftActorList('target left actor list during actual recruitment/carry')
            target=targets[0]
            def owned_work(p):
                return p['kind']==color and p['navi_id']==owner and (p['action']==0 or
                    (p['action']==4 and p['stuck_to']==target['actor_id']) or
                    (p['action']==7 and self.driver.distance(p['position'],target['position'])<80))
            if all(owned_work(p) for p in state['pikis']):break
        else:raise AssertionError('real equipment squad did not enter owned Formation or actual target work')
        self.record('equipment-real-owned-formation-or-target-work',state,requested=count,surviving=len(state['pikis']),
            boundary='grounded captain/squad setup; actual native formation, dig or target-linked transport; no health setters')
        return actor,binding


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

    async def collect(self,source,location):
        if location in self.session.ctx.location_checks[0,source]:
            await self.session.wait_rewards();return {'already_collected':True,'source':source,'location':location}
        route=self.routes[source];game=self.games[source];row=self.rows[location]
        before=await asyncio.to_thread(route.scene,*self.context(location))
        binding=None;attached=None;interruption=None
        try:
            if 'enemy' in row['kind']:
                enemy=next(e for e in before['loaded']['actor_audit']['enemies'] if e['location']==location)
                position=list(enemy['position']);position[0]-=50
                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=30);await asyncio.to_thread(route.playable)
                await asyncio.to_thread(route.command,'actor_defeat',location=location);await asyncio.to_thread(route.playable)
            _,actor,binding=await asyncio.to_thread(route.physical,location,180)
            required=row['pikmin_required'];item_id=self.session.ctx.locations[source][location][0]
            target_name=self.session.items[item_id]['name']
            color=carrier_color(required,binding,target_name,self.session.catalog['buried_treasure'])
            minimum=math.ceil(binding['min_carriers']/10) if color==3 else binding['min_carriers']
            count=min(100,max(2,minimum*2))
            await asyncio.to_thread(route.squad_at_actor,location,color,count)
            attached,_=await asyncio.to_thread(route.attach,location,binding['min_carriers'])
        except (AssertionError,TimeoutError,TargetLeftActorList) as error:
            observed=await asyncio.to_thread(game.wait_state,lambda s:True)
            if observed['physical_deliveries'].get(str(location),0)<=before['physical_deliveries'].get(str(location),0):
                # Actor removal can precede its real Onyon callback/appraisal.
                # A bounded wait may observe that callback; otherwise preserve
                # the actual setup failure, never infer delivery from absence.
                try:
                    await asyncio.to_thread(route.playable)
                    await asyncio.to_thread(route.delivered,location,before,30)
                except (AssertionError,TimeoutError):raise error
            assert location in self.session.native_journal(source)['checks']
            interruption=f'{type(error).__name__}: {error}'
        after=await asyncio.to_thread(route.delivered,location,before,300)
        await asyncio.to_thread(route.playable)
        await self.session.wait_checks({source:[location]},timeout=60);await self.session.wait_rewards(timeout=60)
        for slot,current in self.games.items():self.session.assert_native_reward_state(slot,await asyncio.to_thread(current.wait_state,lambda s:True))
        result={'source':source,'location':location,'original_row':row,'binding':binding,'attached':attached,
            'after':after,'early_actual_arrival_during_setup':interruption,'trace':route.trace.copy(),
            'boundary':'actual per-location Onyon, native check, original-server check and indexed reward required; no global hazard cleanup'}
        self.session.event('equipment-generated-physical-delivery',**result);return result


async def main(args):
    equipment.Equipment=PracticalEquipment
    equipment.HELPERS.extend(Path(__file__).with_name(n) for n in EXTRA);equipment.HELPERS.append(Path(__file__).resolve())
    equipment.HELPERS.append(Path(__file__).with_name('test_gameplay_arrival_policy.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()))
