"""Run the original Louie goal alone, with ordinary first-Red tutorial completion.

The original goal route remains responsible for real Titan proximity, captured
Louie release, carrying and both real AP goal statuses. Later setup bypasses
campaign travel and squad acquisition; Titan health zero bypasses the boss fight.
"""
from __future__ import annotations
import asyncio
import json
from pathlib import Path
import test_gameplay_original_goals as original
from test_gameplay_real_server import make_parser, run
from test_gameplay_settled_route import SettledRoute
from test_real_server import ROOT, sha

HELPERS = tuple(Path(__file__).with_name(name) for name in (
    'test_gameplay_original_goals.py', 'test_gameplay_settled_route.py',
    'test_gameplay_routes.py', 'test_loaded_gameplay_recruitment.py'))


class LouieRoute(SettledRoute):
    def physical(self, location, timeout=30):
        if location == 201:
            # Louie's own config has nonzero burial depths while Titan still
            # holds him. Wait for the real death-animation release instead of
            # treating those depths as proof of a diggable ground actor.
            state = self.game.wait_state(lambda current: any(
                actor['location'] == location and not actor['captured_now']
                for actor in current.get('loaded', {}).get('actor_audit', {}).get('actors', [])),
                timeout, 'Titan death animation released its actual held Louie')
            self.record('titan-death-animation-released-louie', state)
        return super().physical(location, timeout)


async def accept(session, driver):
    pins = {str(path): sha(path) for path in HELPERS}
    snapshot = session.output / 'executed-dependent-helpers'
    snapshot.mkdir()
    for path in HELPERS:
        (snapshot / path.name).write_bytes(path.read_bytes())
    normal_boot, original_route = driver.boot_day1, original.LoadedRoute

    def boot_with_first_red(game, timeout=300):
        result = normal_boot(game, timeout=timeout)
        route = SettledRoute(game, driver)
        before = route.playable()
        reds = [p for p in before['pikis'] if p['kind'] == 1]
        assert len(reds) == 5, 'fresh original first-day five Reds required'
        identities = {p['actor_id'] for p in reds}
        center = [sum(p['position'][i] for p in reds) / len(reds) for i in range(3)]
        driver.walk_to(game, center, radius=60, timeout=30)
        driver.aim_at(game, center, radius=12)
        game.input(buttons=driver.B, frames=120)
        after = route.playable()
        owner = driver.active_navi(after)['actor_id']
        after = game.wait_state(lambda state: all(p['action'] == 0 and p['navi_id'] == owner
            for p in state['pikis'] if p['actor_id'] in identities), 30,
            'initial five Reds recruited through ordinary whistle/tutorial')
        session.event('ordinary-first-red-recruitment-before-later-setup', before=before, after=after,
                      actor_ids=sorted(identities), shortcuts=[])
        result['state'] = after
        return result

    # Only this test's freshly imported driver and orchestration route factory
    # are composed. No native actor, goal, equipment or AP callback is replaced.
    driver.boot_day1 = boot_with_first_red
    original.LoadedRoute = LouieRoute
    try:
        await original.case_acceptance(0)(session, driver)
        assert all(sha(Path(path)) == value for path, value in pins.items())
        session.event('louie-dependent-helpers-unchanged', helper_sha256=pins)
    finally:
        driver.boot_day1, original.LoadedRoute = normal_boot, original_route


async def main(args):
    directory, seed = original.FIXTURES[0]
    args.fixture = ROOT / 'tests/fixtures' / directory / 'generated'
    manifest = json.loads(args.route_manifest.read_text(encoding='utf8'))
    manifest.update(primary_seed=seed, goal_case=0)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.route_manifest = args.output.parent / (args.output.name + '-route.json')
    assert not args.route_manifest.exists()
    args.route_manifest.write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf8')
    return await run(args, acceptance=accept, scope_gates=(), acceptance_kind='loaded_scene', boundary=__doc__)


if __name__ == '__main__':
    asyncio.run(main(make_parser(__doc__).parse_args()))
