"""Bounded disclosed Red-Pikmin setup for SR128's nearby combat hazards.

Only identified non-treasure Fiery Blowhogs24/Dwarf Orange Bulborbs44 within250
of original SR128 are selected. Later-scene captain/squad setup bypasses travel;
ordinary Red whistle/aim/throws/attacks must reduce actual health and enter the
native death lifecycle. The19-worker crew cannot lift the20-weight target.
The original target, both slots' checks/receipts and subsequent Blue carrying,
specific Onyon arrival and earned fire consumer remain unchanged.
"""
import asyncio
import time
from pathlib import Path
import test_equipment_fresh_original as fresh
import test_equipment_gameplay_real_server as equipment
from test_equipment_recall_approach import RecallApproachEquipment,RecallApproachRoute
from test_equipment_dirigibug import recruit_free_crew,supported_approach
from test_equipment_worker_recovery import xz_distance
from test_gameplay_real_server import make_parser


def nearby_hazards(state,target):
    return [e for e in state['loaded']['actor_audit']['live_enemies']
        if e['enemy_id'] in (24,44) and e['location']<=0 and e['alive'] and e['health']>0
        and xz_distance(e['position'],target['position'])<250]


def native_death(enemy):
    # Tank.h:TANK_Dead0; KochappyBase.h:Dead1/Press8 -> Demo9.
    return enemy['health']<=0 and enemy['state'] in ({0} if enemy['enemy_id']==24 else {1,8,9})


def tracked_enemy(state,previous):
    matches=[e for e in state['loaded']['actor_audit']['live_enemies']
        if e['enemy_id']==previous['enemy_id'] and e['location']<=0]
    assert matches,'identified native combat actor disappeared before death observation'
    current=min(matches,key=lambda e:xz_distance(e['position'],previous['position']))
    assert xz_distance(current['position'],previous['position'])<150,'ambiguous moving native combat actor'
    return current


class SRCombatRoute(RecallApproachRoute):
    def clear_sr_nearby_combat(self,location):
        before,target,binding=self.physical(location)
        if location!=128:return
        assert (before['course'],before['cave'],before['floor'])==(2,2036281395,4)
        assert binding['min_carriers']==20
        hazards=nearby_hazards(before,target)
        assert len(hazards)<=4,'bounded identified near-target combat setup'
        checks={slot:set(self.session.ctx.location_checks[0,slot]) for slot in (1,2)}
        receipts={slot:self.session.native_journal(slot)['receipts'] for slot in (1,2)}
        for hazard in hazards:
            current=tracked_enemy(self.playable(),hazard)
            if native_death(current):continue
            samples=[];damaged=False
            for attempt in range(2):
                near=supported_approach(self,current['position'])
                assert current['position'][1]-near[1]<60,'grounded Red throw approach required'
                self.command('actor_position',actor='navi',index=0,position=near)
                self.game.input(frames=20);self.playable()
                self._cleanup_reserve=True
                try:born=self.command('squad_replace',color=1,count=19,captain=0,position=near)
                finally:self._cleanup_reserve=False
                assert born['last_result']['born']==19
                ids={p['actor_id'] for p in born['pikis'] if p['kind']==1}
                assert len(ids)==19
                self.driver.aim_at(self.game,near,radius=20,timeout=30)
                self.game.input(buttons=self.driver.B,frames=90);self.game.input(frames=8)
                deadline=time.monotonic()+120
                while time.monotonic()<deadline:
                    state=self.playable();current=tracked_enemy(state,current)
                    damaged |= current['health']<hazard['health']
                    live=[p for p in state['pikis'] if p['actor_id'] in ids and p['kind']==1]
                    samples.append({'retrace':state['retrace'],'enemy':current,
                        'live_red_ids':[p['actor_id'] for p in live],
                        'attacking_ids':[p['actor_id'] for p in live if p['action']==5]})
                    if native_death(current):
                        assert damaged,'actual ordinary attack damage required'
                        break
                    if not live:break
                    state=recruit_free_crew(self,state,ids,color=1)
                    current=tracked_enemy(state,current)
                    self.driver.aim_at(self.game,current['position'],radius=15,timeout=30)
                    for _ in range(4):self.game.press(self.driver.A,frames=3)
                    x,y=self.aim(self.playable(),{'position':current['position']})
                    self.game.input(frames=60,cstick_x=x,cstick_y=y)
                else:raise TimeoutError('identified SR combat actor did not complete bounded native death')
                if native_death(current):break
                assert not live,'only complete actual combat-crew loss permits one restage'
            else:raise TimeoutError('identified SR combat actor exhausted two real casualty crews')
            state,same,_=self.physical(location)
            assert same['actor_id']==target['actor_id'] and not same['picked']
            assert checks=={slot:set(self.session.ctx.location_checks[0,slot]) for slot in (1,2)}
            assert receipts=={slot:self.session.native_journal(slot)['receipts'] for slot in (1,2)}
            self.record('actual-identified-sr-red-combat-setup',state,hazard_before=hazard,
                hazard_after=current,samples=samples,target_actor_id=target['actor_id'],boundary=__doc__)

    def squad_at_actor(self,location,color,count):
        if location==128:self.clear_sr_nearby_combat(location)
        return super().squad_at_actor(location,color,count)


class SRCombatEquipment(RecallApproachEquipment):
    def __init__(self,session,driver,games):
        super().__init__(session,driver,games)
        self.routes={slot:SRCombatRoute(game,driver) for slot,game in games.items()}
        for route in self.routes.values():route.session=session


async def main(args):
    fresh.FreshOriginalEquipment=SRCombatEquipment
    equipment.HELPERS.extend(Path(__file__).with_name(name) for name in
        ('test_equipment_recall_approach.py','test_equipment_sr_combat_setup.py'))
    await fresh.main(args)


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