"""Exact Red19/20 case with existing-worker recall and aimed throws.

An ordinary Snow Bulborb corpse can take workers to the native pod. Recall
those same live workers through PAD, then aim at the original AP treasure.
No extra births, target relocation or threshold/Onyon/AP assertion changes.
"""
import asyncio
import sys
import time
from pathlib import Path
import test_gameplay_actor_cases as cases
from test_loaded_gameplay_appraisal import AppraisalRoute, EXTRA
from test_equipment_worker_recovery import route_points, xz_distance
from test_gameplay_real_server import make_parser


class ExistingWorkerRoute(AppraisalRoute):
    def attach(self, location, power, timeout=90):
        if location != 9:
            return super().attach(location, power, timeout)
        initial, _, _ = self.physical(location)
        identities={p['actor_id'] for p in initial['pikis']}
        assert power in (19,20) and len(identities)==power
        assert all(p['kind']==1 for p in initial['pikis'])
        # Leave other cases' timeout untouched. This exact case includes a
        # possible ordinary route-graph round trip to the pod and back.
        deadline=time.monotonic()+max(timeout,180)
        recalls=0
        while time.monotonic()<deadline:
            state,actor,_=self.physical(location)
            assert {p['actor_id'] for p in state['pikis']}==identities, 'exact existing Red squad changed'
            self.record('exact-red-target-progress',state,location=location,required=power)
            if actor['carry_power']>=power:
                return state,actor
            owner=self.driver.active_navi(state)['actor_id']
            free=[p for p in state['pikis'] if p['action']==1 or
                  (p['action']==0 and p['navi_id']!=owner)]
            if free:
                assert recalls<3, 'bounded existing-worker recall exhausted'
                cluster=max(([p for p in free if xz_distance(p['position'],seed['position'])<100]
                             for seed in free),key=len)
                center=[sum(p['position'][i] for p in cluster)/len(cluster) for i in range(3)]
                self.walk_existing_to(center)
                self.driver.aim_at(self.game,center,radius=15,timeout=30)
                self.game.input(frames=8)
                self.game.input(buttons=self.driver.B,frames=120)
                self.game.input(frames=8)
                recalled=self.playable()
                assert {p['actor_id'] for p in recalled['pikis']}==identities
                self.record('exact-red-existing-workers-recalled',recalled,location=location,
                            recalled_ids=[p['actor_id'] for p in cluster])
                recalls+=1
            state,actor,_=self.physical(location)
            self.walk_existing_to(actor['position'],radius=65)
            _,actor,_=self.physical(location)
            self.driver.aim_at(self.game,actor['position'],radius=10,timeout=30)
            for _ in range(4):self.game.press(self.driver.A,frames=3)
            self.game.input(frames=20)
        raise TimeoutError(f'exact existing Red workers did not attach at {location}')

    def walk_existing_to(self, target, radius=35):
        state=self.playable()
        start=self.driver.active_navi(state)['position']
        points=route_points(state,start,target,1) if xz_distance(start,target)>140 else [target]
        for index,point in enumerate(points):
            self.driver.walk_to(self.game,point,radius=radius if index==len(points)-1 else 35,timeout=30)


if __name__=='__main__':
    args=make_parser(__doc__).parse_args();args.case='loaded';cases.StableRoute=ExistingWorkerRoute
    cases.EXTRA.extend(Path(__file__).with_name(n) for n in EXTRA)
    cases.EXTRA.extend(Path(__file__).with_name(n) for n in
        ('test_loaded_gameplay_precise.py','test_gameplay_arrival_policy.py','test_loaded_gameplay_appraisal.py',
         'test_equipment_worker_recovery.py','test_equipment_resupply.py','test_equipment_capacity.py',
         'test_equipment_lift.py','test_equipment_glint_press.py','test_equipment_practical.py',
         'test_equipment_charged.py','test_loaded_gameplay_workers.py'))
    # Pin the complete imported local-helper closure, including the existing
    # route graph primitive's transitive imports. No executing helper is edited.
    cases.EXTRA.extend(Path(module.__file__).resolve() for module in list(sys.modules.values())
        if getattr(module,'__file__',None) and
        Path(module.__file__).resolve().parent==Path(__file__).resolve().parent)
    asyncio.run(cases.main(args))
