"""Recover existing native workers after a positive-consumer carry drops.

No recovery births, item relocation, health or effect setters are used. The
controller recruits existing survivors, walks the actual native route graph,
then aims/throws at the current pellet. Actual lift, Onyon and AP remain strict.
"""
import asyncio
import heapq
import json
import math
import time
from pathlib import Path
import test_equipment_gameplay_real_server as equipment
from test_equipment_resupply import ResupplyEquipment, ResupplyRoute, NativeCasualties, capacity, native_pod, EXTRA
from test_gameplay_real_server import make_parser, run


def xz_distance(a, b):
    return math.hypot(a[0] - b[0], a[2] - b[2])


def route_points(state, start, target, color):
    nodes = {n['id']: n for n in state['loaded']['routes'] if not n['closed'] and (color == 0 or not n['water'])}
    assert nodes, 'native walkable route nodes required for existing-worker recovery'
    origin = min(nodes, key=lambda i: xz_distance(nodes[i]['position'], start))
    goal = min(nodes, key=lambda i: xz_distance(nodes[i]['position'], target))
    edges = {i: set() for i in nodes}
    for i, node in nodes.items():
        for other in node['from'] + node['to']:
            if other in nodes:
                edges[i].add(other); edges[other].add(i)
    queue = [(0, origin)]; best = {origin: 0}; previous = {}
    while queue:
        distance, current = heapq.heappop(queue)
        if distance != best[current]: continue
        if current == goal: break
        for other in edges[current]:
            candidate = distance + xz_distance(nodes[current]['position'], nodes[other]['position'])
            if candidate < best.get(other, float('inf')):
                best[other] = candidate; previous[other] = current; heapq.heappush(queue, (candidate, other))
    assert goal in best, 'actual native route graph has no compatible worker-recovery path'
    path = [goal]
    while path[-1] != origin: path.append(previous[path[-1]])
    return [nodes[i]['position'] for i in reversed(path)] + [target]


class RecoveryRoute(ResupplyRoute):
    def attach_target_only(self, location, timeout=90):
        """Assign recalled survivors by actual aimed throws, without swarm."""
        deadline = time.monotonic() + timeout
        while time.monotonic() < deadline:
            state, actor, binding = self.physical(location)
            if actor['picked']:
                return state, actor
            live = [p for p in state['pikis'] if p['actor_id'] in self.main_ids]
            if capacity(live, self.delivery_color) < binding['min_carriers']:
                raise NativeCasualties('actual main capacity loss during target-only throws')
            self.driver.walk_to(self.game, actor['position'], radius=65, timeout=45)
            state, actor, _ = self.physical(location)
            if actor['picked']:
                return state, actor
            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'actual native lift missing after exclusive target throws for {location}')

    def attach(self, location, power, timeout=90):
        if getattr(self, '_recovering_workers', False):
            return self.attach_target_only(location, timeout)
        try:
            return super().attach(location, power, timeout)
        except TimeoutError:
            # A competing corpse can return live workers to the pod before
            # the first treasure lift, just as hazards can drop a later load.
            for attempt in range(3):
                state, actor, _ = self.physical(location)
                if actor['picked']:
                    return state, actor
                try:
                    self.recover_existing(location)
                    state, actor, _ = self.physical(location)
                    assert actor['picked'], 'worker recovery must observe the actual native lift'
                    return state, actor
                except TimeoutError:
                    if attempt == 2:
                        raise

    def walk_existing(self, target):
        state = self.playable(); start = self.driver.active_navi(state)['position']
        points = route_points(state, start, target, self.delivery_color)
        self.record('existing-worker-native-route-walk', state, points=points,
            boundary='ordinary PAD walking over read-only native route nodes; no actor relocation or births')
        for position in points:
            self.driver.walk_to(self.game, position, radius=35, timeout=60)
            self.playable()

    def recover_existing(self, location):
        before, actor, binding = self.physical(location)
        if actor['picked']:
            self.parked_for_carry = False
            return False
        ids = {p['actor_id'] for p in before['pikis']}
        main = [p for p in before['pikis'] if p['actor_id'] in self.main_ids and p['kind'] == self.delivery_color]
        if capacity(main, self.delivery_color) < binding['min_carriers']:
            raise NativeCasualties('actual main capacity fell below weight during carry recovery')
        owner = self.driver.active_navi(before)['actor_id']
        workers = [p for p in main if p['action'] == 0 and p['navi_id'] == owner]
        candidates = [p for p in main if p['action'] != 4]
        recall_transport = not candidates and not workers
        if recall_transport:
            # Competing corpses can occupy every survivor without either load
            # meeting its minimum. Ordinary B may recall those real carriers.
            candidates = main
        if candidates:
            clusters = [[p for p in candidates if xz_distance(p['position'], seed['position']) < 100]
                        for seed in candidates]
            cluster = max(clusters, key=len)
        else:
            cluster = []
        if not workers or len(cluster) > len(workers):
            for recall in range(4):
                assert cluster, 'no existing native worker cluster available to recall'
                center = [sum(p['position'][i] for p in cluster) / len(cluster) for i in range(3)]
                self.walk_existing(center)
                self.driver.aim_at(self.game, center, radius=20, timeout=60)
                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']
                workers = [p for p in state['pikis'] if p['actor_id'] in self.main_ids and p['action'] == 0
                           and p['navi_id'] == owner]
                assert workers, 'real whistle did not recruit an existing worker'
                if not recall_transport or capacity(workers, self.delivery_color) >= binding['min_carriers']:
                    break
                candidates = [p for p in state['pikis'] if p['actor_id'] in self.main_ids
                              and not (p['action'] == 0 and p['navi_id'] == owner)]
                clusters = [[p for p in candidates if xz_distance(p['position'], seed['position']) < 100]
                            for seed in candidates]
                cluster = max(clusters, key=len) if clusters else []
            else:
                raise TimeoutError('four ordinary existing-carrier recall clusters exhausted')
        center = [sum(p['position'][i] for p in workers) / len(workers) for i in range(3)]
        if xz_distance(self.driver.active_navi(self.playable())['position'], center) > 60:
            self.walk_existing(center)
        self.walk_existing(actor['position'])
        state, same, _ = self.physical(location)
        assert same['actor_id'] == actor['actor_id'], 'recovery must retain the same native pellet'
        assert {p['actor_id'] for p in state['pikis']} <= ids, 'existing-worker recovery cannot birth or replace Pikmin'
        self.record('actual-existing-worker-recovery', state, selected_actor_ids=[p['actor_id'] for p in workers],
            before_actor_ids=sorted(ids), target=actor,
            boundary='existing live Formation/whistled survivors walked by actual PAD; target and native weights unchanged')
        self._recovering_workers = True
        try:
            self.attach(location, binding['min_carriers'], timeout=90)
        finally:
            self._recovering_workers = False
        self.parked_for_carry = False
        return True

    def await_delivery(self, location, baseline, color, minimum, timeout=600):
        deadline = time.monotonic() + timeout; deficient = 0; recoveries = 0
        while time.monotonic() < deadline:
            state = self.playable()
            if state['physical_deliveries'].get(str(location), 0) > baseline['physical_deliveries'].get(str(location), 0):
                return self.record('actual-specific-onyon-arrival', state, location=location)
            live = [p for p in state['pikis'] if p['actor_id'] in self.main_ids]
            deficient = deficient + 1 if capacity(live, color) < minimum else 0
            if deficient >= 3: raise NativeCasualties('native casualty capacity loss before actual Onyon arrival')
            target = next((p for p in state['pellets'] if p['location_id'] == location), None)
            if target and not target['picked']:
                if recoveries >= 3: raise TimeoutError('three bounded existing-worker carry recoveries exhausted')
                recoveries += int(self.recover_existing(location))
                continue
            if target and target['picked'] and not self.parked_for_carry:
                pod = native_pod(state); safe = list(pod['position']); safe[0] -= 60
                safe = self.command('ground_query', position=safe)['last_result']['position']; safe[1] += 5
                self.command('actor_position', actor='navi', index=0, position=safe)
                self.parked_for_carry = True
            self.game.input(frames=20)
        raise TimeoutError(f'actual specific Onyon arrival missing for equipment source {location}')


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


async def main(args):
    equipment.Equipment = RecoveryEquipment
    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',
        'test_equipment_resupply.py', 'test_equipment_capacity.py', 'test_equipment_lift.py',
        'test_equipment_glint_press.py', 'test_equipment_worker_recovery.py'))
    report = await run(args, acceptance=equipment.accept, scope_gates=(), acceptance_kind='loaded_scene', boundary=__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()))
