"""Positive equipment consumers with disclosed native hazard activation/resupply.

Later-scene/captain/squad setup bypasses acquisition and combat. Genuine Pikmin
activate authored hidden enemies, native hazards may kill them, and a bounded
replacement squad can continue at the target's actual native position. Checks,
rewards, effects, attachment, digging and Onyon arrival are never assigned.
The independent exact carrier-threshold acceptance remains unchanged.
"""
import asyncio
import json
import math
import time
from pathlib import Path
import test_equipment_gameplay_real_server as equipment
from test_equipment_charged import ChargedEquipment, EXTRA
from test_equipment_practical import PracticalRoute, carrier_color
from test_equipment_capacity import NativeCasualties, capacity
from test_equipment_lift import ActualLift
from test_equipment_glint_press import release_glint
from test_loaded_gameplay_real_server import LoadedRoute, SETUP
from test_gameplay_real_server import make_parser, run


def exclude_pod_reserve(main_ids, state, position):
    candidates = [p for p in state['pikis'] if p['kind'] == 0 and p['navi_id'] == 0
                  and math.dist(p['position'], position) < 20]
    assert len(candidates) == 1, 'actual free Blue reserve must be uniquely observed at its pod birth position'
    reserve = candidates[0]
    # Native Piki pool pointers can be reused if a main actor dies between the
    # two births. A pointer is not a permanent role assignment.
    return set(main_ids) - {reserve['actor_id']}, reserve


def native_pod(state):
    # ItemOnyon.h: native POD=3 in caves, SHIP=4 on the overworld.
    expected = 3 if state['cave'] else 4
    pods = [o for o in state['onyons'] if o['type'] == expected]
    assert len(pods) == 1, 'the actual native pod/ship must be uniquely observed'
    return pods[0]


class ResupplyRoute(ActualLift, PracticalRoute):
    def _command_with_movie_guard(self, op, fields, raw=False):
        # The read-only ground query has a source-backed pre-effect section()
        # guard in addition to the queued mutation Busy protocol. A newly
        # starting real discovery movie may win after the prior snapshot.
        for attempt in range(8):
            try:
                invoke = LoadedRoute.command if raw else super().command
                return invoke(self, op, **fields) if raw else invoke(op, **fields)
            except RuntimeError as error:
                detail = str(error).removeprefix('native gameplay harness: ')
                if detail != 'finish the normal movie/menu before loaded setup':
                    raise
                cleared = self.game.command('state')
                self.record('actual-pre-effect-movie-guard-refusal', cleared, op=op, attempt=attempt + 1)
                self.playable()
        raise TimeoutError(f'bounded native pre-effect movie-guard retries exhausted: {op}')

    def command(self, op, **fields):
        return self._command_with_movie_guard(op, fields)

    def free_birth(self, color, position):
        origin = list(position); origin[0] += 40
        return self._command_with_movie_guard('squad_setup',
            dict(color=color, count=1, captain=0, position=origin), raw=True)

    def activate_hidden_enemy(self, location, color):
        before = self.playable()
        enemy = next(e for e in before['loaded']['actor_audit']['enemies'] if e['location'] == location)
        ground = self.command('ground_query', position=enemy['position'])['last_result']['position']
        if enemy['position'][1] < ground[1] + 80:
            # Ordinary ground enemies such as the Burrowing Snagret still
            # require real proximity before their native emergence FSM runs.
            near = list(ground); near[0] -= 50
            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=30)
            return self.playable()
        born = self.free_birth(color, ground)
        assert born['last_result']['born'] == 1
        samples = []; deadline = time.monotonic() + 90
        while time.monotonic() < deadline:
            self.game.input(frames=30); state = self.playable()
            current = next(e for e in state['loaded']['actor_audit']['enemies'] if e['location'] == location)
            samples.append({'retrace': state['retrace'], 'enemy': current})
            if current['position'][1] < ground[1] + 50 or not current['alive']:
                self.record('actual-pikmin-proximity-enemy-activation', state, enemy_before=enemy,
                    samples=samples, boundary='one real Pikmin birth/placement; original hidden-enemy lifecycle activates before health-zero combat shortcut')
                return state
        raise TimeoutError(f'original hidden enemy {location} did not activate from genuine Pikmin proximity')

    def squad_at_actor(self, location, color, count):
        self.delivery_color = color
        _, actor, binding = self.physical(location)
        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
        self.main_ids = {p['actor_id'] for p in born['pikis']}
        pod = native_pod(born)
        reserve = self.command('ground_query', position=pod['position'])['last_result']['position']
        reserve_born = self.free_birth(0, reserve)
        assert reserve_born['last_result']['born'] == 1
        self.main_ids, reserve_actor = exclude_pod_reserve(self.main_ids, reserve_born, reserve)
        self.record('actual-free-pod-reserve-role', reserve_born, reserve=reserve_actor,
            main_actor_ids=sorted(self.main_ids), boundary='free Blue at observed pod birth position is excluded from delivery capacity even if its native pool pointer was reused')
        self.parked_for_carry = False
        for _ in range(6):
            state = self.playable()
            live = [p for p in state['pikis'] if p['actor_id'] in self.main_ids]
            if capacity(live, color) < binding['min_carriers']:
                raise NativeCasualties('native hazards reduced the prepared delivery squad below actual carrier capacity')
            center = [sum(p['position'][i] for p in live) / len(live) for i in range(3)]
            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']
            targets = [p for p in state['pellets'] if p['location_id'] == location]
            if not targets:
                return actor, binding
            target = targets[0]
            ready = [p for p in state['pikis'] if p['actor_id'] in self.main_ids and
                p['navi_id'] == owner and (p['action'] == 0 or
                (p['action'] in (4, 7) and self.driver.distance(p['position'], target['position']) < 90))]
            if capacity(ready, color) >= binding['min_carriers']:
                self.record('actual-positive-delivery-squad-with-pod-reserve', state,
                    requested=count, main_actor_ids=sorted(self.main_ids), capacity=capacity(ready, color),
                    boundary='real owned Formation/dig/transport; separate free reserve at actual pod prevents unrelated total-extinction fixture exit')
                return actor, binding
        raise AssertionError('sufficient live actors failed actual owned Formation or target work')

    def await_delivery(self, location, baseline, color, minimum, timeout=150):
        deadline = time.monotonic() + timeout; deficient = 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 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.record('consumer-fixture-captain-returned-to-pod', state,
                    boundary='captain setup after actual lift; native target and carriers continue their own route')
                self.parked_for_carry = True
            self.game.input(frames=20)
        raise TimeoutError(f'actual specific Onyon arrival missing for equipment source {location}')


class ResupplyEquipment(ChargedEquipment):
    def __init__(self, session, driver, games):
        super().__init__(session, driver, games)
        self.routes = {slot: ResupplyRoute(game, driver) for slot, 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))
        if 'enemy' in row['kind']:
            enemy = next(e for e in before['loaded']['actor_audit']['enemies'] if e['location'] == location)
            if enemy['enemy_id'] == 10:
                # Glint Beetles do not release treasure from health zero.
                # Real Purple landing/quake must drive their native Press FSM.
                press = await asyncio.to_thread(release_glint, route, location)
                self.session.event('actual-glint-original-treasure-release', evidence=press)
            else:
                required = row['pikmin_required']
                color = 0 if 'blue' in required else 4 if 'white' in required else 1
                active = await asyncio.to_thread(route.activate_hidden_enemy, location, color)
                enemy = next(e for e in active['loaded']['actor_audit']['enemies'] if e['location'] == location)
                if enemy['alive'] and enemy['health'] > 0:
                    await asyncio.to_thread(route.command, 'actor_defeat', location=location)
                    await asyncio.to_thread(route.playable)
        _, _, binding = await asyncio.to_thread(route.physical, location, 180)
        item_id = self.session.ctx.locations[source][location][0]
        color = carrier_color(row['pikmin_required'], binding, self.session.items[item_id]['name'], self.session.catalog['buried_treasure'])
        minimum = binding['min_carriers']; count = min(99, max(2, math.ceil(minimum / (10 if color == 3 else 1)) * 2))
        waves = []
        for wave in range(6):
            journal = self.session.native_journal(source)
            try:
                await asyncio.to_thread(route.squad_at_actor, location, color, count)
                await asyncio.to_thread(route.attach, location, minimum, 60)
                after = await asyncio.to_thread(route.await_delivery, location, before, color, minimum)
                break
            except (NativeCasualties, TimeoutError) as error:
                observed = await asyncio.to_thread(route.playable)
                if observed['physical_deliveries'].get(str(location), 0) > before['physical_deliveries'].get(str(location), 0):
                    after = observed; break
                current = self.session.native_journal(source)
                if location in current['checks'] and location not in journal['checks']:
                    # The native callback/journal can precede publication of
                    # the matching read-only Onyon counter snapshot.
                    after = await asyncio.to_thread(route.await_delivery, location, before, color, minimum, 30)
                    break
                assert current['checks'] == journal['checks'] and current['receipts'] == journal['receipts']
                surviving = [p for p in observed['pikis'] if p['actor_id'] in route.main_ids]
                if capacity(surviving, color) >= minimum:
                    # Aiming/path/recruitment timeouts with an adequate live
                    # squad are not casualty evidence and remain strict.
                    raise
                waves.append({'wave': wave + 1, 'reason': f'{type(error).__name__}: {str(error)[:250]}', 'state': observed})
                self.session.event('actual-native-casualties-before-fixture-resupply', source=source, location=location, wave=waves[-1],
                    boundary='no check/reward or target relocation; bounded positive-consumer fixture resupply, not a no-casualty/combat claim')
        else:
            raise AssertionError(f'equipment source {location} exceeded six native hazard/resupply waves')
        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,
            'after': after, 'resupply_waves': waves, 'trace': route.trace.copy(), 'boundary': __doc__}
        self.session.event('equipment-generated-physical-delivery', **result)
        return result


async def main(args):
    equipment.Equipment = ResupplyEquipment
    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'))
    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()))
