"""Private native DD184 carry diagnosis; no AP server or equipment-consumer claim.

Uses disclosed scene/captain/squad setup and an enemy-health combat shortcut.
Both the original corpse and AP treasure remain native. Only ordinary whistle,
cursor aim, C-stick and A throws may attach carriers or lift the treasure.
"""
import argparse
import hashlib
import importlib.util
import json
import math
from pathlib import Path
import shutil
import sys
import time

from test_gameplay_tutorial import initial_red_intro
from test_equipment_resupply import ResupplyRoute


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def compact(state, target=184):
    return {k: state[k] for k in ('response_id', 'retrace', 'ready', 'movie_state', 'paused')} | {
        'navi': state['navi'], 'pikis': state['pikis'], 'pellets': state['pellets'],
        'target': next((p for p in state['pellets'] if p['location_id'] == target), None)}


def main(args):
    args.output.mkdir(parents=True, exist_ok=False)
    source = args.prepared.resolve()
    assert source.is_relative_to(Path(__file__).resolve().parents[1] / 'output')
    copied = args.output / 'prepared-run'
    shutil.copytree(source, copied, ignore=shutil.ignore_patterns('*.lock', '*.tmp'))
    profile_path = copied / 'profile.json'
    profile = json.loads(profile_path.read_text())
    profile['bridge_dir'] = str((copied / 'bridge').resolve())
    profile['journal_path'] = str((copied / 'journal.json').resolve())
    profile_path.write_text(json.dumps(profile, indent=2) + '\n')
    driver_path = args.output / 'executed-driver.py'
    shutil.copyfile(args.driver, driver_path)
    spec = importlib.util.spec_from_file_location('targeted_throw_driver', driver_path)
    driver = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(driver)
    tools = Path(__file__).resolve().parent
    inputs = {Path(__file__).resolve(), source / 'profile.json', source / 'bridge/runtime-config.json'}
    inputs.update(Path(m.__file__).resolve() for m in list(sys.modules.values())
        if getattr(m, '__file__', None) and Path(m.__file__).resolve().parent == tools)
    report = {'status': 'running', 'boundary': __doc__, 'native_sha256': sha(args.native),
        'driver_sha256': sha(driver_path), 'input_sha256': {str(p): sha(p) for p in inputs}}
    old_spec = importlib.util.spec_from_file_location('targeted_throw_legacy_lift', args.legacy_lift)
    old_lift = importlib.util.module_from_spec(old_spec); old_spec.loader.exec_module(old_lift)
    report['input_sha256'][str(args.legacy_lift.resolve())] = sha(args.legacy_lift)
    game = driver.GameplayClient(args.native, args.assets, profile_path,
        args.output / 'control', copied / 'save', args.output / 'native.log')
    try:
        game.start(); report['pid'] = game.process.pid
        report['entry'] = initial_red_intro(game, driver)
        route = ResupplyRoute(game, driver)
        route.scene(3, 1818177587, 2)
        route.activate_hidden_enemy(184, 4)
        route.command('actor_defeat', location=184)
        route.playable()
        route.physical(184, 180)
        if args.white_threshold:
            # Construct the blocked native19 condition through ordinary A
            # throws. Neither object is removed, repositioned or assigned
            # carriers; the actual corpse remains an alternative work target.
            state, target, _ = route.physical(184)
            near = list(target['position']); near[0] -= 65
            near = route.command('ground_query', position=near)['last_result']['position']; near[1] += 5
            route.command('actor_position', actor='navi', index=0, position=near)
            born = route._command_with_movie_guard('squad_replace',
                dict(color=4, count=19, captain=0, position=near), raw=True)
            assert born['last_result']['born'] == 19
            # Only19 Whites exist, so even generous speed contribution cannot
            # legitimately satisfy the20 literal-weight threshold.
            game.input(buttons=driver.B, frames=90); game.input(frames=8)
            threshold_samples = []; deadline = time.monotonic() + 120
            while time.monotonic() < deadline:
                state, target, _ = route.physical(184)
                threshold_samples.append(compact(state))
                assert not target['picked'], '19 actual Whites must not lift20 weight'
                if target['carry_power'] == 57:
                    report['nineteen_blocked'] = compact(state)
                    break
                driver.aim_at(game, target['position'], radius=10, timeout=30)
                for _ in range(4): game.press(driver.A, frames=3)
                game.input(frames=30); route.playable()
            else:
                raise TimeoutError('nineteen actual target attachments were not reached')
            report['threshold_samples'] = threshold_samples
            # Recruit the additive Free White far outside the carriers'
            # whistle radius. They must remain attached while it is recruited.
            far = list(target['position']); far[0] -= 220
            far = route.command('ground_query', position=far)['last_result']['position']; far[1] += 5
            route.command('actor_position', actor='navi', index=0, position=far)
            born = route.free_birth(4, far); assert born['last_result']['born'] == 1
            game.input(buttons=driver.B, frames=90); game.input(frames=8)
            state, still, _ = route.physical(184)
            assert still['carry_power'] == 57 and not still['picked']
            report['additive_free_recruited'] = compact(state)
            near = list(target['position']); near[0] -= 45
            near = route.command('ground_query', position=near)['last_result']['position']; near[1] += 5
            route.command('actor_position', actor='navi', index=0, position=near)
            game.input(frames=150); route.playable()
            # Match the proposed canonical aim+four standard A3 burst exactly.
            driver.aim_at(game, target['position'], radius=10, timeout=30)
            report['exact_burst_before'] = compact(game.wait_state(lambda s: True))
            for _ in range(4): game.press(driver.A, frames=3)
            for _ in range(50):
                game.input(frames=6); state = route.playable()
                p = next((p for p in state['pellets'] if p['location_id'] == 184), None)
                if p and p['picked']:
                    report['lifted'] = compact(state); report['status'] = 'passed'; break
            else: raise TimeoutError('twentieth actual White did not lift after exact target-specific A3 burst')
            report['trace'] = route.trace
            return
        route.squad_at_actor(184, 4, 40)
        report['after_squad'] = compact(route.playable())
        try:
            old_lift.ActualLift.attach(route, 184, 20, 45)
        except TimeoutError as error:
            report['legacy_attach_timeout'] = str(error)
        state = route.playable()
        report['before_targeted_throw'] = compact(state)
        if next(p for p in state['pellets'] if p['location_id'] == 184)['picked']:
            report['status'] = 'control_lifted_without_targeted_throw'
            return
        deadline = time.monotonic() + 120
        attempts = []
        while time.monotonic() < deadline:
            state, target, binding = route.physical(184)
            if target['picked']:
                report['lifted'] = compact(state)
                report['status'] = 'passed'
                break
            # Retain any real available Formation worker first. Recruit a
            # distant Free actor only if there is none, without whistling
            # the target carriers off their slots.
            owner = driver.active_navi(state)['actor_id']
            formation = [p for p in state['pikis'] if p['kind'] == 4 and p['action'] == 0 and p['navi_id'] == owner]
            free = [p for p in state['pikis'] if p['kind'] == 4 and p['action'] == 1
                and math.dist(p['position'], target['position']) > 160]
            if not formation and free:
                worker = free[0]
                near = list(worker['position']); near[0] -= 25
                near = route.command('ground_query', position=near)['last_result']['position']; near[1] += 5
                route.command('actor_position', actor='navi', index=0, position=near)
                driver.aim_at(game, worker['position'], radius=15, timeout=25)
                game.input(buttons=driver.B, frames=60); game.input(frames=8)
                route.playable()
            state = route.playable(); target = next(p for p in state['pellets'] if p['location_id'] == 184)
            near = list(target['position']); near[0] -= 45
            near = route.command('ground_query', position=near)['last_result']['position']; near[1] += 5
            route.command('actor_position', actor='navi', index=0, position=near)
            game.input(frames=120); route.playable()
            driver.aim_at(game, target['position'], radius=12, timeout=25)
            aimed = game.wait_state(lambda s: True)
            owner = driver.active_navi(aimed)['actor_id']
            formation = [p for p in aimed['pikis'] if p['kind'] == 4 and p['action'] == 0 and p['navi_id'] == owner]
            assert formation, 'a genuine recruited White must be available to throw'
            attempts.append({'before': compact(aimed), 'formation': formation,
                'cursor_distance': driver.distance(driver.active_navi(aimed)['cursor'], target['position'])})
            game.press(driver.A, frames=6)
            for _ in range(25):
                game.input(frames=6); observed = route.playable()
                pellet = next((p for p in observed['pellets'] if p['location_id'] == 184), None)
                attempts[-1].setdefault('observations', []).append(compact(observed))
                if pellet and pellet['picked']:
                    report['lifted'] = compact(observed); report['status'] = 'passed'; break
            if report['status'] == 'passed': break
        else:
            raise TimeoutError('target-specific actual White throws did not produce native lift')
        report['targeted_throw_attempts'] = attempts
        assert report['status'] == 'passed'
        report['trace'] = route.trace
    except BaseException as error:
        report['status'] = 'failed'
        report['failure'] = f'{type(error).__name__}: {error}'[:2000]
        raise
    finally:
        game.shutdown()
        report['native_exit_code'] = game.process.returncode if game.process else None
        report['inputs_unchanged'] = all(sha(Path(p)) == v for p, v in report['input_sha256'].items())
        (args.output / 'report.json').write_text(json.dumps(report, indent=2) + '\n')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(__doc__)
    for name in ('prepared', 'output', 'native', 'assets', 'driver'):
        parser.add_argument('--' + name, type=Path, required=True)
    parser.add_argument('--legacy-lift', type=Path, required=True)
    parser.add_argument('--white-threshold', action='store_true')
    main(parser.parse_args())
