"""Equipment consumers with disclosed real-Pikmin activation of nearby cave traps.

Original DD floor2 Bomb-rocks use the Pikmin-proximity drop lifecycle. A genuine
test Pikmin activates each nearby trap before the delivery squad is prepared.
The engine performs the drop, countdown, explosion and death. This isolates
equipment consumers from trap avoidance/combat; neither is claimed by this scope.
"""
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
from test_loaded_gameplay_real_server import LoadedRoute
from test_gameplay_real_server import make_parser, run


def near_bombs(state, position):
    return [e for e in state['loaded']['actor_audit']['live_enemies']
        if e['enemy_id'] == 36 and e['alive'] and
        math.hypot(e['position'][0] - position[0], e['position'][2] - position[2]) < 250]


class BombBaitRoute(PracticalRoute):
    def squad_at_actor(self, location, color, count):
        if location == 184:
            _, actor, _ = self.physical(location)
            target = actor['position']
            before = self.session.native_journal(self.slot)
            for _ in range(12):
                state = self.playable()
                bombs = near_bombs(state, target)
                if not bombs:
                    break
                bomb = bombs[0]
                # Preserve the existing squad at the actual cave pod; only the
                # disclosed bait enters the authored Pikmin-trigger radius.
                pod = next(o for o in state['onyons'] if o['type'] == 4)
                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)
                ids = {p['actor_id'] for p in state['pikis']}
                bait = self.command('ground_query', position=bomb['position'])['last_result']['position']
                # The existing fixture's first real birth is origin.x - 40.
                origin = list(bait); origin[0] += 40
                born = LoadedRoute.command(self, 'squad_setup', color=4, count=1, captain=0, position=origin)
                added = [p for p in born['pikis'] if p['actor_id'] not in ids]
                assert len(added) == 1 and added[0]['kind'] == 4
                assert self.driver.distance(added[0]['position'], bait) < bomb['private_radius']
                samples = []; deadline = time.monotonic() + 90
                while time.monotonic() < deadline:
                    self.game.input(frames=30); observed = self.playable()
                    remaining = near_bombs(observed, target)
                    samples.append({'retrace': observed['retrace'], 'bombs': remaining,
                                    'piki_count': len(observed['pikis'])})
                    if len(remaining) < len(bombs):
                        break
                else:
                    raise TimeoutError('native Pikmin-triggered Bomb-rock did not complete its drop/explosion')
                after = self.session.native_journal(self.slot)
                assert after['checks'] == before['checks'] and after['receipts'] == before['receipts']
                self.record('actual-bait-pikmin-native-bomb-lifecycle', observed,
                    bomb_before=bomb, bait=added[0], observations=samples,
                    boundary='real bait birth/placement setup; native proximity, drop, countdown, blast and death; no combat or trap-avoidance claim')
            else:
                raise AssertionError('nearby original bomb traps exceeded bounded fixture setup')
        return super().squad_at_actor(location, color, count)


class BombBaitEquipment(ChargedEquipment):
    def __init__(self, session, driver, games):
        super().__init__(session, driver, games)
        self.routes = {slot: BombBaitRoute(game, driver) for slot, game in games.items()}
        for slot, route in self.routes.items():
            route.session = session; route.slot = slot


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