"""Open real cave gates by ordinary recalled-Pikmin swarm before delivery.

Closed native waypoint positions are set by actual ItemGate actors. This route
uses existing workers, normal PAD whistle/swarm and autonomous BreakGate work;
only the actual final-segment waypoint reopening permits the carry to resume.
No gate, treasure, item, health or check setter is used by this obstacle policy.
"""
import asyncio
import heapq
import json
import time
from pathlib import Path
import test_equipment_gameplay_real_server as equipment
from test_equipment_lighting_route import LightingEquipment, SOURCE
from test_equipment_dirigibug import recruit_free_crew
from test_equipment_worker_recovery import RecoveryRoute, EXTRA, native_pod, capacity, NativeCasualties, xz_distance
from test_gameplay_real_server import make_parser, run


def delivery_path(state, target, color):
    nodes = {n['id']: n for n in state['loaded']['routes'] if color == 0 or not n['water']}
    assert nodes, 'native compatible delivery route required'
    start = min(nodes, key=lambda i: xz_distance(nodes[i]['position'], target))
    goal = min(nodes, key=lambda i: xz_distance(nodes[i]['position'], native_pod(state)['position']))
    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)
    best = {start: 0}; previous = {}; queue = [(0, start)]
    while queue:
        cost, current = heapq.heappop(queue)
        if cost != best[current]: continue
        if current == goal: break
        for other in edges[current]:
            candidate = cost + xz_distance(nodes[current]['position'], nodes[other]['position']) + 1000000 * nodes[other]['closed']
            if candidate < best.get(other, float('inf')):
                best[other] = candidate; previous[other] = current; heapq.heappush(queue, (candidate, other))
    assert goal in best, 'actual target has no compatible native pod route'
    path = [goal]
    while path[-1] != start: path.append(previous[path[-1]])
    return [nodes[i] for i in reversed(path)]


class GateRoute(RecoveryRoute):
    def clear_persistent_geysers(self, location, carrier_color):
        """Disclosed later-scene immune-squad setup; actual attack/death only."""
        state, actor, binding = self.physical(location)
        path = delivery_path(state, actor['position'], carrier_color)
        points = [actor['position']] + [node['position'] for node in path]
        immune = {20: 1, 21: 4, 22: 2}
        hazards = [e for e in state['loaded']['actor_audit']['live_enemies']
            if e['enemy_id'] in immune and immune[e['enemy_id']] != carrier_color
            and e['alive'] and e['health'] > 0 and e['state'] != 0
            and min(xz_distance(e['position'], point) for point in points) < 180]
        assert len(hazards) <= 16, 'bounded authored persistent-geyser 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:
            count = min(10, binding['min_carriers'] - 1)
            assert count > 0, 'immune cleanup must remain below actual target lift threshold'
            near = list(hazard['position']); near[0] -= 65
            near = self.command('ground_query', position=near)['last_result']['position']; near[1] += 5
            self.command('actor_position', actor='navi', index=0, position=near)
            self.game.input(frames=20); self.playable()
            born = self.command('squad_replace', color=immune[hazard['enemy_id']], count=count, captain=0, position=near)
            assert born['last_result']['born'] == count
            ids = {p['actor_id'] for p in born['pikis']}
            self.driver.aim_at(self.game, near, radius=20, timeout=60)
            self.game.input(buttons=self.driver.B, frames=120); self.game.input(frames=8)
            deadline = time.monotonic() + 120; samples = []; damaged = False
            while time.monotonic() < deadline:
                state = self.playable()
                matches = [e for e in state['loaded']['actor_audit']['live_enemies']
                    if e['enemy_id'] == hazard['enemy_id'] and xz_distance(e['position'], hazard['position']) < 1]
                assert len(matches) == 1, 'actual stationary geyser identity must remain unique'
                current = matches[0]
                damaged |= current['health'] < hazard['health']
                samples.append({'retrace': state['retrace'], 'health': current['health'], 'state': current['state'],
                    'attacking_ids': [p['actor_id'] for p in state['pikis'] if p['actor_id'] in ids and p['action'] == 5]})
                if current['state'] == 0:
                    assert damaged and current['health'] <= 0, 'actual immune-Pikmin damage and native death required'
                    self.record('actual-immune-pikmin-geyser-cleared', state, hazard_before=hazard,
                        hazard_after=current, samples=samples, target_actor_id=actor['actor_id'],
                        boundary='later-scene immune squad/captain setup bypasses travel/acquisition; actual ordinary Piki attacks and native geyser death, no health setter')
                    break
                recruit_free_crew(self, state, ids, color=immune[hazard['enemy_id']])
                self.driver.aim_at(self.game, hazard['position'], radius=15, timeout=60)
                for _ in range(4): self.game.press(self.driver.A, frames=3)
                x, y = self.aim(self.playable(), {'position': hazard['position']})
                self.game.input(frames=90, cstick_x=x, cstick_y=y)
            else:
                raise TimeoutError('immune Pikmin did not complete actual persistent-geyser death')
            _, same, _ = self.physical(location)
            assert same['actor_id'] == actor['actor_id'], 'cleanup must preserve the native treasure actor'
        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)}

    def squad_at_actor(self, location, color, count):
        self.clear_persistent_geysers(location, color)
        return super().squad_at_actor(location, color, count)

    def open_delivery_gates(self, location):
        for _ in range(4):
            state, actor, binding = self.physical(location)
            path = delivery_path(state, actor['position'], self.delivery_color)
            blocked = next((i for i, node in enumerate(path) if node['closed']), None)
            if blocked is None:
                return
            assert blocked > 0, 'need an actual open approach node before a closed gate'
            gate = path[blocked]; approach = path[blocked - 1]
            self.walk_existing(approach['position'])
            self.driver.aim_at(self.game, actor['position'], 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']
            assert any(p['actor_id'] in self.main_ids and p['action'] == 0 and p['navi_id'] == owner
                       for p in state['pikis']), 'ordinary whistle must recall actual main gate workers'
            self.driver.walk_to(self.game, gate['position'], radius=40, timeout=60)
            self.record('actual-native-gate-approach', self.playable(), location=location, gate_waypoint=gate,
                target_actor_id=actor['actor_id'], boundary='actual closed ItemGate waypoint; ordinary existing-Pikmin whistle and walk')
            deadline = time.monotonic() + 240; seen_break = False
            while time.monotonic() < deadline:
                state = self.playable()
                node = next(n for n in state['loaded']['routes'] if n['id'] == gate['id'])
                breaking = [p for p in state['pikis'] if p['actor_id'] in self.main_ids and p['action'] == 6]
                if breaking:
                    seen_break = True
                    self.record('actual-pikmin-break-gate', state, gate_waypoint=gate['id'], worker_ids=[p['actor_id'] for p in breaking])
                if not node['closed']:
                    assert seen_break, 'actual native BreakGate action must precede final waypoint reopening'
                    self.record('actual-native-gate-final-segment-opened', state, gate_waypoint=node)
                    break
                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 casualty capacity loss during gate work')
                if not breaking:
                    x, y = self.aim(state, {'position': gate['position']})
                    self.game.input(frames=60, cstick_x=x, cstick_y=y)
                else:
                    self.game.input(frames=60)
            else:
                raise TimeoutError('ordinary native gate work did not reopen its actual waypoint')
            state, same, _ = self.physical(location)
            assert same['actor_id'] == actor['actor_id'], 'gate work must preserve the actual target actor'
            self.recover_existing(location)
        raise TimeoutError('four actual native delivery gates exhausted')

    def await_delivery(self, location, baseline, color, minimum, timeout=600):
        state = self.playable()
        if (state['physical_deliveries'].get(str(location), 0) <= baseline['physical_deliveries'].get(str(location), 0)
                and any(p['location_id'] == location for p in state['pellets'])):
            self.open_delivery_gates(location)
        return super().await_delivery(location, baseline, color, minimum, timeout)


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


async def main(args):
    equipment.Equipment = GateEquipment
    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', 'test_equipment_lighting_route.py',
        'test_equipment_gate_route.py'))
    equipment.HELPERS.append(SOURCE)
    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()))
