"""Controlled consumer setup uses the actual living captain and native bombs.

No captain health is restored. SMGC's authored proximity bombs are activated by
real free Blue Pikmin while a reserve and the captain stay at a read-only safe
native waypoint. Actual drop/fuse/explosion remains native; untriggered bombs
are recorded, never declared cleared. Carrier thresholds and delivery stay strict.
"""
import asyncio
import json
import time
from pathlib import Path
import test_equipment_gameplay_real_server as equipment
from test_equipment_gate_route import GateEquipment, GateRoute, EXTRA, SOURCE
from test_equipment_dirigibug import clear_dirigibugs
from test_equipment_worker_recovery import xz_distance
from test_gameplay_real_server import make_parser, run


def living_captain(state):
    navis = state['navi']; captains = state['effects']['captains']
    assert len(navis) == len(captains), 'native actor and indexed captain observers must agree'
    active = next(i for i, navi in enumerate(navis) if navi['active'])
    selected = captains[active]
    assert selected['health'] > 0, 'fixture must use a genuinely living active captain'
    return selected['index']


class SurvivorRoute(GateRoute):
    def clear_native_producers(self, location):
        before, target, _ = self.physical(location)
        if not any(e['enemy_id'] == 58 and e['alive'] and e['health'] > 0
                   for e in before['loaded']['actor_audit']['live_enemies']):
            return
        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)}
        result = clear_dirigibugs(self, location=location)
        _, same, _ = self.physical(location)
        assert same['actor_id'] == target['actor_id'], 'producer combat must preserve the original native treasure'
        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-native-bomb-producers-cleared', result['state'], location=location,
            target_actor_id=target['actor_id'], producers=result['producers'], boundary=result['boundary'])

    def _command_with_movie_guard(self, op, fields, raw=False):
        fields = dict(fields)
        if op in ('squad_setup', 'squad_replace', 'effect_consumer_probe') or (op == 'actor_position' and fields['actor'] == 'navi'):
            state = self.game.wait_state(lambda s: True)
            selected = living_captain(state)
            field = 'index' if op == 'actor_position' else 'captain'
            if fields.get(field, 0) != selected:
                self.record('actual-living-captain-fixture-selection', state, op=op,
                    requested=fields.get(field, 0), selected=selected,
                    boundary='existing live active captain selected; no revival, health or state assignment')
            fields[field] = selected
        result = super()._command_with_movie_guard(op, fields, raw)
        if op == 'squad_replace' and getattr(self, '_cleanup_reserve', False):
            pod = next(o for o in result['onyons'] if o['type'] == 3)
            safe = super()._command_with_movie_guard('ground_query', dict(position=pod['position']))['last_result']['position']
            assert self.free_birth(0, safe)['last_result']['born'] == 1
            self.record('actual-cleanup-free-pod-reserve', self.playable(), position=safe,
                boundary='one actual free Blue at native pod preserves a living reserve during disclosed immune cleanup; no health restoration')
        return result

    def activate_smgc_bombs(self, location):
        state, actor, _ = self.physical(location)
        if (state['course'], state['cave'], state['floor']) != (2, 2036281396, 3):
            return
        bombs = [e for e in state['loaded']['actor_audit']['live_enemies'] if e['enemy_id'] == 36 and e['alive']]
        volatile = [e for e in state['loaded']['actor_audit']['live_enemies']
                    if e['enemy_id'] == 93 and e['alive'] and e['health'] > 0]
        triggers = bombs + volatile
        if not triggers:
            return
        assert len(triggers) <= 20, 'bounded authored SMGC bomb activation'
        candidates = [n['position'] for n in state['loaded']['routes'] if not n['closed']]
        safe = max(candidates, key=lambda p: min(xz_distance(p, b['position']) for b in triggers))
        assert min(xz_distance(safe, b['position']) for b in triggers) > 250, 'actual captain staging must be outside bomb blast area'
        safe = self.command('ground_query', position=safe)['last_result']['position']; safe[1] += 5
        self.command('actor_position', actor='navi', index=0, position=safe)
        reserve = self.free_birth(0, safe)
        assert reserve['last_result']['born'] == 1
        bait_positions = []
        for bomb in triggers:
            ground = self.command('ground_query', position=bomb['position'])['last_result']['position']
            born = self.free_birth(0, ground)
            assert born['last_result']['born'] == 1
            bait_positions.append(ground)
        deadline = time.monotonic() + 60; samples = []; changed = False
        while time.monotonic() < deadline:
            self.game.input(frames=60); current = self.playable()
            remaining = [e for e in current['loaded']['actor_audit']['live_enemies'] if e['enemy_id'] == 36 and e['alive']]
            volatile_remaining = [e for e in current['loaded']['actor_audit']['live_enemies']
                                  if e['enemy_id'] == 93 and e['alive'] and e['health'] > 0]
            armed = [b for b in remaining if b['state'] == 1 or b['health'] < 4.5]
            changed |= len(remaining) < len(bombs) or bool(armed)
            samples.append({'retrace': current['retrace'], 'bombs': remaining, 'volatile_dweevils': volatile_remaining})
            if not volatile_remaining and (not remaining or (changed and not armed and len(samples) >= 10)):
                self.record('actual-smgc-proximity-bomb-setup', current, before_bombs=bombs,
                    before_volatile_dweevils=volatile, samples=samples, remaining_bombs=remaining,
                    remaining_volatile_dweevils=volatile_remaining, actual_one_pikmin_birth_positions=bait_positions,
                    boundary='later-scene free Blue bait at actual bomb ground positions, captain/reserve staged away; actual native activation/fuse/explosion, remaining untriggered bombs not claimed cleared')
                return
        raise TimeoutError('bounded SMGC native bomb activation/fuse did not settle')

    def clear_persistent_geysers(self, location, carrier_color):
        self._cleanup_reserve = True
        try:
            result = super().clear_persistent_geysers(location, carrier_color)
        finally:
            self._cleanup_reserve = False
        self.clear_native_producers(location)
        self.activate_smgc_bombs(location)
        return result


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

    async def recovered(self, slot, captain=0):
        state = await asyncio.to_thread(self.routes[slot].playable)
        return await super().recovered(slot, living_captain(state))


async def main(args):
    equipment.Equipment = SurvivorEquipment
    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', 'test_equipment_dirigibug.py', 'test_equipment_survivor_setup.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()))
