"""Drive the real Pikmin 2 loop through PAD input and read-only engine snapshots.



Requires player-owned extracted US resources. No callback or save serializer is

called by this driver. All processes and saves belong to the supplied test run.

"""

from __future__ import annotations

import argparse

import json

import math

import os

from pathlib import Path

import subprocess

import time



A, B, X, Y, START, Z, L, R = 0x100, 0x200, 0x400, 0x800, 0x1000, 0x10, 0x40, 0x20

UP, DOWN, LEFT, RIGHT = 8, 4, 1, 2





class GameplayClient:

    def __init__(self, native, assets_parent, profile, control_dir, save_dir, log_path):

        self.native = Path(native).resolve()

        self.assets_parent = Path(assets_parent).resolve()

        self.profile = Path(profile).resolve()

        self.control_dir = Path(control_dir).resolve()

        self.game_dir = self.control_dir.parent / "game"

        self.save_dir = Path(save_dir).resolve()

        self.log_path = Path(log_path).resolve()

        self.process = None

        self.log = None

        self.sequence = 0

        self.transcript_path = self.control_dir / "commands.jsonl"



    def start(self):

        if not (self.assets_parent / "assets/user/Kando/aiConstants.txt").is_file():

            raise RuntimeError("assets_parent must contain the real extracted US assets/ tree")

        self.control_dir.mkdir(parents=True, exist_ok=True)

        self.game_dir.mkdir(parents=True, exist_ok=True)

        self.save_dir.mkdir(parents=True, exist_ok=True)

        self.log_path.parent.mkdir(parents=True, exist_ok=True)

        for name in ("control.json", "state.json", "state.json.tmp"):

            (self.control_dir / name).unlink(missing_ok=True)

        assets_link = self.game_dir / "assets"

        assets_target = self.assets_parent / "assets"

        if assets_link.exists():

            if assets_link.resolve() != assets_target.resolve():

                raise RuntimeError("test game cwd contains a different assets tree")

        elif os.name == "nt":

            subprocess.run(["cmd", "/c", "mklink", "/J", str(assets_link), str(assets_target)],

                           check=True, capture_output=True)

        else:

            assets_link.symlink_to(assets_target, target_is_directory=True)

        env = dict(os.environ, PIKMIN2_SAVE_DIR=str(self.save_dir), SDL_AUDIODRIVER="dummy")

        self.log = self.log_path.open("wb")

        self.process = subprocess.Popen(

            [str(self.native), "--ap-profile", str(self.profile), "--ap-gameplay-test", str(self.control_dir)],

            cwd=self.game_dir, env=env, stdin=subprocess.DEVNULL,

            stdout=self.log, stderr=subprocess.STDOUT,

            creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0)

        return self



    def state(self):

        if self.process and self.process.poll() is not None:

            raise RuntimeError(f"test-owned native exited {self.process.returncode}; inspect {self.log_path}")

        try:

            return json.loads((self.control_dir / "state.json").read_bytes())

        except (FileNotFoundError, json.JSONDecodeError, PermissionError):

            return None



    def wait_state(self, predicate, timeout=30, description="state condition"):

        until = time.monotonic() + timeout

        last = None

        while time.monotonic() < until:

            last = self.state()

            if last and last.get("error") and last.get("response_id",0)>=self.sequence:

                raise RuntimeError(f"native gameplay harness: {last['error']}")

            if last and predicate(last):

                return last

            time.sleep(.05)

        raise TimeoutError(f"{description}: {json.dumps(last, ensure_ascii=True)}; log {self.log_path}")



    def command(self, op, timeout=120, **fields):

        self.sequence += 1

        payload = dict(id=self.sequence, op=op, **fields)

        temp = self.control_dir / "control.json.tmp"

        temp.write_text(json.dumps(payload), encoding="utf-8")

        until = time.monotonic() + 2

        while True:

            try:

                temp.replace(self.control_dir / "control.json")

                break

            except PermissionError:

                if time.monotonic() >= until:

                    raise

                time.sleep(.01)

        result = self.wait_state(lambda s: s["response_id"] >= self.sequence, timeout, f"command {payload}")

        with self.transcript_path.open("a", encoding="utf-8") as out:

            out.write(json.dumps(dict(request=payload, process_pid=self.process.pid if self.process else None,

                ack={key:result.get(key) for key in ("response_id","retrace","input_remaining","section","game_state","day","ready","delivery_count","card_saves","card_loads")})) + "\n")

        return result



    def input(self, buttons=0, frames=6, stick_x=0, stick_y=0, cstick_x=0, cstick_y=0, wait=True):

        state = self.command("input", buttons=buttons, frames=frames, stick_x=stick_x,

                             stick_y=stick_y, cstick_x=cstick_x, cstick_y=cstick_y)

        if wait:

            state = self.wait_state(lambda s: s["input_remaining"] == 0,

                                    max(120, frames / 20 + 10), "PAD interval consumed")

        return state



    def press(self, buttons, frames=4):

        self.input(buttons=buttons, frames=frames)

        return self.input(frames=4)



    def shutdown(self):

        if self.process and self.process.poll() is None:

            try:

                self.command("quit", timeout=3)

                self.process.wait(timeout=8)

            except (RuntimeError, TimeoutError, subprocess.TimeoutExpired):

                self.process.terminate()

                try:

                    self.process.wait(timeout=5)

                except subprocess.TimeoutExpired:

                    self.process.kill()

                    self.process.wait(timeout=5)

        if self.log:

            self.log.close()

            self.log = None





def active_navi(state):

    return next((n for n in state.get("navi", []) if n["active"]), None)





def distance(a, b):

    return math.hypot(a[0] - b[0], a[2] - b[2])





def live_scene(client, timeout=150):

    """Wait through ordinary tutorial/movie UI without altering game state."""

    deadline=time.monotonic()+timeout

    while time.monotonic()<deadline:

        state=client.wait_state(lambda s:True)

        if state.get("ready") and not state.get("movie_state") and active_navi(state):

            return state

        client.press(A)

        if state.get("movie_state") or state.get("paused") or state.get("movie_pause"):

            client.press(START)

    raise TimeoutError("normal tutorial/movie did not resume")





def follow_waypoints(client, positions, radius=30):

    trace=[]

    for target in positions:

        trace.extend(walk_to(client,target,radius=radius,timeout=45))

    return trace





def aim_at(client, target, radius=12, timeout=15):

    """Move the real cursor with a partial main stick; never write actor state."""

    deadline=time.monotonic()+timeout

    while time.monotonic()<deadline:

        state=live_scene(client); navi=active_navi(state)

        cursor=navi.get("cursor")

        if cursor is None:

            raise RuntimeError("cursor readback requires merged model10 or later")

        gap=distance(cursor,target)

        if gap<=radius:

            client.input(frames=2)

            return state

        dx,dz=(target[0]-cursor[0])/gap,(target[2]-cursor[2])/gap

        side,front=navi["camera_side"],navi["camera_front"]

        sn,fn=math.hypot(side[0],side[2]),math.hypot(front[0],front[2])

        x=-(dx*side[0]+dz*side[2])/sn

        y=(dx*front[0]+dz*front[2])/fn

        # Below CursorMovementStick, above NeutralStickThreshold: the ordinary

        # Navi::makeVelocity branch turns toward the cursor without walking.

        client.input(frames=max(1,min(5,round(gap/8))),stick_x=round(40*x),stick_y=round(40*y))

    raise TimeoutError(f"normal cursor could not reach {target}; last cursor {cursor}")





def whistle_here(client, frames=120):

    state=live_scene(client)

    if "cursor" in active_navi(state):

        aim_at(client,active_navi(state)["position"],radius=20)

    return client.input(buttons=B,frames=frames)





def pluck_sprouts(client, timeout=120):

    """Approach and pluck actual nearby seeds around the day-one red Onion."""

    deadline=time.monotonic()+timeout

    while time.monotonic()<deadline:

        state=live_scene(client)

        if not state.get("sprouts"):

            return state

        seed=min(state["sprouts"],key=lambda p:distance(p["position"],active_navi(state)["position"]))["position"]

        onion=next(o for o in state["onyons"] if o["type"]==1)["position"]

        pos=active_navi(state)["position"]

        angle=math.atan2(pos[0]-onion[0],pos[2]-onion[2])

        target=math.atan2(seed[0]-onion[0],seed[2]-onion[2])

        delta=(target-angle+math.pi)%(2*math.pi)-math.pi

        # Keep the walk outside the actual Onion collision cylinder.

        path=[[onion[0]+150*math.sin(angle),onion[1],onion[2]+150*math.cos(angle)]]

        steps=max(1,math.ceil(abs(delta)/(math.pi/3)))

        path += [[onion[0]+150*math.sin(angle+delta*i/steps),onion[1],onion[2]+150*math.cos(angle+delta*i/steps)] for i in range(1,steps+1)]

        follow_waypoints(client,path,radius=22)

        walk_to(client,seed,radius=22,timeout=25)

        client.press(A,frames=12)

        client.input(frames=90)

    raise TimeoutError("ordinary seed plucking did not finish")





def raise_day1_squad(client, timeout=480):

    """Normal first enemy, captain switch, Onion, five flowers and paper bag.



    Positions are authored VoR route waypoints, not actor relocation commands.

    Every additional Pikmin comes from real carried pellets and native plucking.

    """

    deadline=time.monotonic()+timeout
    initial=live_scene(client)
    if not hasattr(client,"day1_initial_piki_ids"):
        if len(initial.get("pikis",[]))!=5:
            raise RuntimeError("fresh day-one route must observe the original five real Pikmin")
        client.day1_initial_piki_ids={p["actor_id"] for p in initial["pikis"]}

    def first_corpse(state):

        return any(p["text_id"]=="Kochappy" for p in state.get("pellets",[]))

    if not first_corpse(client.wait_state(lambda s:True)):

        walk_to(client,[-590,0,2800],radius=55)

        client.input(buttons=B,frames=120)

        live_scene(client)

        # The first whistle starts x02; after that authored demo, call again

        # with a real cursor centered on the surviving initial red cluster.

        state=client.wait_state(lambda s:True)

        initial=state.get("pikis",[])

        center=[sum(p["position"][i] for p in initial)/len(initial) for i in range(3)]

        walk_to(client,center,radius=40)

        aim_at(client,center,radius=15)

        client.input(buttons=B,frames=120)

        fight_deadline=time.monotonic()+90

        while time.monotonic()<fight_deadline:

            state=live_scene(client)

            if first_corpse(state):break

            enemies=state.get("loaded",{}).get("actor_audit",{}).get("live_enemies",[])

            near=[e for e in enemies if e.get("alive") and distance(e["position"],active_navi(state)["position"])<250]

            target=min(near,key=lambda e:distance(e["position"],active_navi(state)["position"]))["position"] if near else [-590,0,2783]

            walk_to(client,target,radius=85,timeout=25)

            aim_at(client,target,radius=15)

            for _ in range(8):client.press(A,frames=12)

            client.input(frames=120)

        else:raise RuntimeError("actual first enemy did not die through normal attacks")

    client.input(frames=180)

    for _ in range(6):

        client.press(Y,frames=12)

        client.input(frames=90)

        state=live_scene(client)

        if len(state.get("navi",[]))>1 and state["navi"][1]["active"]:

            break

    else:raise RuntimeError("ordinary captain switch remained locked after the real enemy tutorial")

    follow_waypoints(client,[[-976,-46,4356],[-756,35,4316],[-530,60,4190]],radius=30)

    walk_to(client,[-342,60,3933],radius=120)

    live_scene(client)

    pluck_sprouts(client)

    return farm_and_reunite(client,timeout=max(180,deadline-time.monotonic()))





def farm_and_reunite(client,timeout=480):

    """Continue the normal Louie seed/flower phase and collapse the real bag."""

    deadline=time.monotonic()+timeout

    # All five authored number heads must actually reach the Onion. Incidental

    # neighboring flower hits are valid: follow live actors instead of assuming

    # that the selected head is the one carried first.

    while time.monotonic()<deadline:

        state=live_scene(client)

        heads=[p for p in state.get("pellets",[]) if p["kind"]==0]

        if not heads:

            client.input(frames=180)

            pluck_sprouts(client)

            break

        candidates=[p for p in heads if not p.get("picked")]

        if not candidates:

            client.input(frames=120)

            continue

        head=min(candidates,key=lambda p:distance(p["position"],active_navi(state)["position"]))

        walk_to(client,head["position"],radius=95,timeout=30)

        aim_at(client,head["position"],radius=16)

        for _ in range(3):client.press(A,frames=6)

        client.input(frames=180)

        # With only Louie's first red, the next available thrower is a seed

        # produced by this actual delivery. Wait for carrying heads to finish

        # rather than throwing at another flower with an empty squad.

        transport_deadline=time.monotonic()+60

        while time.monotonic()<transport_deadline:

            observed=live_scene(client)

            if not any(p["kind"]==0 and p.get("picked") for p in observed.get("pellets",[])):

                break

            client.input(frames=120)

        client.input(frames=180)

        pluck_sprouts(client)

        whistle_here(client)

    else:

        raise TimeoutError("normal flower harvest did not finish")

    state=whistle_here(client)

    if len(state.get("pikis",[]))<16:

        raise RuntimeError("normal flower route did not raise sixteen real reds")

    initial_ids=client.day1_initial_piki_ids
    louie_ids={p["actor_id"] for p in state["pikis"]}-initial_ids
    if len(louie_ids)<11:
        raise RuntimeError("normal flower route did not produce Louie's eleven real reds")
    select_captain(client,1)
    state=gather_day1_group(client,louie_ids,timeout=180)
    active=active_navi(state)["actor_id"]
    if sum(p["actor_id"] in louie_ids and p["navi_id"]==active and p["action"]==0 for p in state["pikis"])<11:
        raise RuntimeError("Louie's eleven actual reds were not all recruited before leaving the Onion")
    return reunite_captains(client)





def reunite_captains(client):

    """Throw the observed squads onto the authored fifteen-weight paper bag."""

    # Reach the west face of the fifteen-weight bag using the authored ramp.

    follow_waypoints(client,[[-705,55,3740],[-950,59,3518],[-1200,55,3325],[-1342,38,3205],[-1427,30,2983],[-1030,0,2870]],radius=30)

    walk_to(client,[-1000,0,2800],radius=18)

    return press_day1_bag(client)





def select_captain(client,index):
    state=live_scene(client)
    desired=state["navi"][index]["actor_id"]
    if active_navi(state)["actor_id"]!=desired:
        client.press(Y,frames=12)
        client.input(frames=45)
        state=live_scene(client)
    if active_navi(state)["actor_id"]!=desired:
        raise RuntimeError(f"normal captain switch did not select index {index}")
    return state


def day1_on_bag(piki):
    # Actual unflattened bag platform is at y44.7. A remote idle red at the
    # Onion must never be merged into the original corpse-carrier cluster.
    return piki["position"][1]>25 and distance(piki["position"],[-910,0,2769])<130


def day1_needs_recruitment(state,actor_ids):
    active=active_navi(state)["actor_id"]
    return [p for p in state["pikis"] if p["actor_id"] in actor_ids and not day1_on_bag(p)
            and not (p["navi_id"]==active and p["action"]==0)]


def gather_day1_group(client,actor_ids,timeout=180):
    """Whistle observed individual actors, preserving the two genuine squads."""
    deadline=time.monotonic()+timeout
    while time.monotonic()<deadline:
        state=live_scene(client);navi=active_navi(state)
        candidates=day1_needs_recruitment(state,actor_ids)
        if not candidates:return state
        target=min(candidates,key=lambda p:distance(p["position"],navi["position"]))["position"]
        # A straggler on Louie's plateau needs its authored ramp, not a straight
        # line through the cliff. This branch normally runs before leaving it.
        if target[2]>3200 and navi["position"][2]<3200:
            follow_waypoints(client,[[-1427,30,2983],[-1342,38,3205],[-1200,55,3325],[-950,59,3518],[-705,55,3740]],radius=30)
            state=live_scene(client);navi=active_navi(state)
        onion=next((o["position"] for o in state.get("onyons",[]) if o["type"]==1),None)
        if onion and distance(target,onion)<200 and distance(navi["position"],onion)<450:
            pos=navi["position"]
            angle=math.atan2(pos[0]-onion[0],pos[2]-onion[2])
            end=math.atan2(target[0]-onion[0],target[2]-onion[2])
            delta=(end-angle+math.pi)%(2*math.pi)-math.pi
            steps=max(1,math.ceil(abs(delta)/(math.pi/3)))
            points=[[onion[0]+150*math.sin(angle),onion[1],onion[2]+150*math.cos(angle)]]
            points += [[onion[0]+150*math.sin(angle+delta*i/steps),onion[1],onion[2]+150*math.cos(angle+delta*i/steps)] for i in range(1,steps+1)]
            follow_waypoints(client,points,radius=25)
        walk_to(client,target,radius=35,timeout=40)
        aim_at(client,target,radius=15)
        client.input(frames=8) # a new whistle edge even after a prior held B
        client.input(buttons=B,frames=120)
        client.input(frames=8)
    raise TimeoutError(f"normal whistle could not recruit actor group {sorted(actor_ids)}")


def press_day1_bag(client):
    """Recruit the actual actor groups and throw until real bag weight collapses."""
    initial_ids=client.day1_initial_piki_ids
    trace=[]
    for index in (0,1,0,1):
        state=select_captain(client,index)
        bag=next(b for b in state["bags"] if b["required"]==15)
        if bag["pressed"]:break
        group=initial_ids if index==0 else {p["actor_id"] for p in state["pikis"]}-initial_ids
        state=gather_day1_group(client,group,timeout=180)
        if index==1 and active_navi(state)["position"][2]>3200:
            follow_waypoints(client,[[-705,55,3740],[-950,59,3518],[-1200,55,3325],[-1342,38,3205],[-1427,30,2983]],radius=30)
        walk_to(client,[-850,0,2797] if index==0 else [-1000,0,2800],radius=15 if index==0 else 18,timeout=45)
        aim_at(client,[-920,45,2790] if index==0 else [-950,45,2810],radius=15)
        for _ in range(40):
            state=client.wait_state(lambda s:True);bag=next(b for b in state["bags"] if b["required"]==15)
            active=active_navi(state)["actor_id"]
            followers=sum(p["navi_id"]==active and p["action"]==0 for p in state["pikis"])
            trace.append(dict(retrace=state["retrace"],captain=index,bag=bag,formation=followers))
            if bag["pressed"]:break
            if bag["current"]>=bag["required"]:
                client.input(frames=120)
                continue
            if not followers:break
            client.press(A,frames=12)
        client.input(frames=120)
    observed=client.wait_state(lambda s:True)
    if not any(b.get("pressed") and b.get("required")==15 for b in observed.get("bags",[])) and observed.get("movie")!="x06_join":
        raise RuntimeError(f"real paper-bag weight remained insufficient after adaptive throws: {trace[-5:]}")
    state=client.wait_state(lambda s:s.get("movie")=="x06_join" or any(b.get("pressed") and b.get("required")==15 for b in s.get("bags",[])),30,"actual paper bag weight collapse")
    live_scene(client)
    walk_to(client,[-970,6,2825],radius=15)
    whistle_here(client,180)
    return dict(state=client.wait_state(lambda s:True),trace=trace,shortcuts=[])


def accept_newgame_defaults(client):
    """Select Start in the compiled PIKI_P2_HOST three-row native SDL prompt.

    The native handler applies direction before accept in one poll. A combined
    UP/A edge wraps the default first row to Start and accepts before wall-clock
    direction repeat can advance it again. Bounded retries cover prior partial
    navigation without changing Normal/Standard option values.
    """
    for _ in range(3):
        state=client.wait_state(lambda s:True)
        if not state.get("host_newgame_prompt"):
            return state
        client.input(frames=30)  # arm the host overlay with all buttons released
        client.press(UP|A,frames=12)
    return client.wait_state(lambda s:not s.get("host_newgame_prompt"),20,
                             "normal default rules and Start accepted")



def boot_day1(client, timeout=180, world_map=False):

    """Use actual title/file-select/new-game input; return the first live scene."""

    deadline = time.monotonic() + timeout

    trace = []

    while time.monotonic() < deadline:

        state = client.wait_state(lambda s: True, min(30, max(1, deadline-time.monotonic())), "normal boot")

        trace.append({k: state.get(k) for k in ("section", "game_state", "movie", "day", "ready", "card_saves", "card_loads", "file_select", "host_newgame_prompt")})

        if world_map and state.get("game_state")==1 and state.get("card_loads",0)>0:

            return dict(state=state,trace=trace,shortcuts=[])

        if not world_map and state.get("game_state")==1:

            # A saved campaign resumes at the real map. START would open its

            # Return to Title dialog, so land through the ordinary area UI.

            course=state.get("effects",{}).get("worldmap",{}).get("selected",0)

            landing=choose_course(client,course,timeout=max(60,deadline-time.monotonic()))

            trace.append({"normal_saved_landing":landing["trace"]})

            return dict(state=landing["state"],trace=trace,shortcuts=[])

        if state.get("ready") and state.get("movie_state",0)==0 and active_navi(state):

            return dict(state=state, trace=trace, shortcuts=[])

        if state.get("host_captain_select"):

            client.input(frames=12)  # arm the normal SDL captain screen

            client.press(START,frames=12)  # accept its ordinary default pair

            client.wait_state(lambda s:not s.get("host_captain_select"),20,"normal captain defaults accepted")

            continue

        if state.get("host_newgame_prompt"):
            accept_newgame_defaults(client)
            continue

        files = state.get("file_select", {})

        if files.get("state") == 4:

            card_state = files.get("card_state")

            if card_state not in (0, 1, 11, 22, 26):

                raise RuntimeError(f"test-owned card failed ordinary file creation: {files}")

            if files.get("card_input_delay", 1):

                client.input(frames=30)

            elif files.get("card_screen") == 1:

                # The real CreateNewFile dialog defaults to No; choose Yes.

                if not files.get("card_selection"):

                    client.input(stick_x=-90, frames=4)

                    client.input(frames=4)

                client.press(A)

            else:

                client.press(A)

            continue

        if files.get("state") == 5:

            if files.get("menu_state") == 4:

                client.press(A)

            else:

                client.input(frames=20)

            continue

        # Start/A are ordinary menu and skippable-movie inputs. They do not

        # initialize PlayData or choose a synthetic section.

        client.press(START)

        client.press(A)

        time.sleep(.4)

    raise TimeoutError(f"normal title/new-game entry failed: {trace[-20:]}")





def load_saved_worldmap(client,timeout=240):

    """Select the real existing file and await a successful native card load."""

    return boot_day1(client,timeout=timeout,world_map=True)





def choose_course(client,course,timeout=180):

    """Use actual world-map arrows, Land confirmation and the normal loader."""

    if course not in range(4):raise ValueError("native course must be 0..3")

    deadline=time.monotonic()+timeout;trace=[]

    while time.monotonic()<deadline:

        state=client.wait_state(lambda s:True)

        trace.append({key:state.get(key) for key in ("retrace","game_state","course","movie","effects")})

        if state.get("game_state") in (3,4) and state.get("ready") and not state.get("movie_state") and state.get("course")==course:

            return dict(state=state,trace=trace,shortcuts=[])

        world=state.get("effects",{}).get("worldmap")

        if state.get("game_state")==1 and world:

            selectable={c["id"] for c in world["courses"] if c["selectable"]}

            if course not in selectable:raise RuntimeError(f"actual world-map course {course} is locked")

            selected=world["selected"]

            if world["state"]==2 and selected!=course:

                # Native WorldMap::getTarget adjacency (including sparse AP

                # globe unlocks); breadth-first search only selectable courses.

                edges={0:[(1,RIGHT),(2,UP)],1:[(0,LEFT),(3 if 3 in selectable else 2,UP)],

                       2:[(0,DOWN),(3 if 3 in selectable else 1,RIGHT)],3:[(2,LEFT),(1,DOWN)]}

                queue=[(selected,[])];seen={selected};route=None

                while queue:

                    current,path=queue.pop(0)

                    if current==course:route=path;break

                    for nxt,button in edges[current]:

                        if nxt in selectable and nxt not in seen:

                            seen.add(nxt);queue.append((nxt,path+[button]))

                if not route:raise RuntimeError(f"no selectable normal world-map path {selected}->{course}")

                client.press(route[0],frames=12)

            elif world["state"] in (2,9):

                client.press(A,frames=12)

            else:client.input(frames=30)

        elif state.get("game_state") in (3,4):

            # A skip pressed on the final movie tick can open the ordinary

            # pause page. Use the same observed tutorial/pause policy here.

            live_scene(client,timeout=120)

        elif state.get("movie_state") and state.get("game_state")!=1:

            client.press(A)

            client.press(START)

        else:client.input(frames=30)

    raise TimeoutError(f"normal world-map landing did not complete: {trace[-8:]}")





def withdraw_reds(client,timeout=90):

    """Use the real Onion transfer menu and let exitPikis spawn stored reds."""

    initial=live_scene(client)

    onion=next(o for o in initial["onyons"] if o["type"]==1)

    walk_to(client,onion["position"],radius=40,timeout=30)

    client.press(A,frames=12)

    state=client.wait_state(lambda s:s.get("onion_menu") is not None or s.get("ui_scene")==10004,15,"real Onion menu")

    deadline=time.monotonic()+timeout;trace=[]

    while time.monotonic()<deadline:

        trace.append(state.get("onion_menu",{}))

        if state.get("onion_menu",{}).get("state")==1 and state["onion_menu"]["in_onion"]==0:

            break

        state=client.input(buttons=DOWN,frames=120)

        client.input(frames=6)

        if "onion_menu" not in state:break # earlier readback version: one normal held DOWN

    client.press(A,frames=12)

    live_scene(client)

    state=client.input(frames=240)

    return dict(state=state,trace=trace,shortcuts=[])





select_course=choose_course





def boot_title(client,timeout=120,after_opens=0):

    """Advance normal startup to an observed TitleMenu::open, before Story."""

    deadline=time.monotonic()+timeout;trace=[]

    while time.monotonic()<deadline:

        state=client.wait_state(lambda s:True)

        trace.append({k:state.get(k) for k in ("retrace","effects","game_state")})

        if state.get("effects",{}).get("title_menu_opens",0)>after_opens:

            return dict(state=state,trace=trace,shortcuts=[])

        client.press(START,frames=8)

        client.input(frames=15)

    raise TimeoutError("ordinary TitleMenu did not open")





def return_title(client,timeout=120):

    """Choose the world's ordinary Return to Title confirmation."""

    state=client.wait_state(lambda s:s.get("game_state")==1 and s.get("effects",{}).get("worldmap",{}).get("state")==2,40,"idle world map before title return")

    opens=state.get("effects",{}).get("title_menu_opens",0)

    client.press(START,frames=12)

    client.wait_state(lambda s:s.get("effects",{}).get("worldmap",{}).get("state")==8,15,"normal Return to Title prompt")

    client.input(frames=75) # real dialog's 0.8-second input delay

    client.press(DOWN,frames=8) # native out_menu_1 is Return to Title

    client.press(A,frames=12)

    client.wait_state(lambda s:s.get("game_state")!=1,45,"ordinary world-map exit")

    return boot_title(client,timeout=timeout,after_opens=opens)





def return_worldmap(client,timeout=240):

    """Choose Pause/R/Go to Sunset/Yes, then actual results and card save."""

    state=live_scene(client)

    if state.get("game_state")!=3 or state.get("day",0)<1:

        raise RuntimeError("normal Sunset requires a playable overworld after day one")

    saves=state.get("card_saves",0)

    client.press(START,frames=12)

    client.wait_state(lambda s:s.get("ui_scene")==10013,15,"ordinary Radar pause page")

    client.input(frames=45)

    client.press(R,frames=12)

    client.wait_state(lambda s:s.get("ui_scene")==10010,15,"ordinary pause menu page")

    client.input(frames=60) # native menu's one-second input delay

    client.press(DOWN,frames=8)

    client.press(A,frames=12)

    client.input(frames=60) # native Sunset confirmation delay

    client.press(UP,frames=8)

    client.press(A,frames=12)

    result=finish_day_and_save(client,timeout=timeout)

    if result["state"].get("card_saves",0)<=saves:

        raise RuntimeError("Sunset completed without an observed successful native card save")

    return result





def walk_to(client, target, radius=35, timeout=60):

    deadline = time.monotonic() + timeout

    trace = []

    while time.monotonic() < deadline:

        state = live_scene(client,timeout=120)

        navi = active_navi(state)

        position = navi["position"]

        gap = distance(position, target)

        trace.append(position)

        if gap <= radius:

            client.input(frames=1)

            return trace

        dx,dz=(target[0]-position[0])/gap,(target[2]-position[2])/gap

        side,front=navi["camera_side"],navi["camera_front"]

        sn,fn=math.hypot(side[0],side[2]),math.hypot(front[0],front[2])

        # Exact inverse of Navi::makeVelocity: x=-mainStickX, z=mainStickY,

        # result = normalized camera side*x + normalized camera front*z.

        x=-(dx*side[0]+dz*side[2])/sn

        y=(dx*front[0]+dz*front[2])/fn

        # Shorten the final step: fixed twelve-frame strides overshoot the

        # plucking radius and can hit the Onion before returning past a seed.

        frames=max(1,min(8,math.ceil((gap-radius)/6)))

        client.input(frames=frames, stick_x=round(65*x), stick_y=round(65*y))

    raise TimeoutError(f"captain route stalled toward {target}, recent positions {trace[-12:]}")





def carry_location(client, location, timeout=180):

    """Throw actual followers and await their normal transport/suction caller."""

    initial=client.wait_state(lambda s:True)

    count=initial.get("physical_deliveries",{}).get(str(location),0)

    deliveries=initial.get("delivery_count",0)

    def arrived(s):

        return (s.get("physical_deliveries",{}).get(str(location),0)>count or

            (s.get("delivery_count",0)>deliveries and s.get("last_delivery_location")==location))

    deadline=time.monotonic()+timeout; trace=[]

    while time.monotonic()<deadline:

        state=client.wait_state(lambda s:arrived(s) or (s.get("ready") and active_navi(s)),40)

        if arrived(state):

            return dict(state=state,trace=trace,shortcuts=[])

        target=next((p for p in state.get("pellets",[]) if p.get("location_id")==location),None)

        if target is None:

            # Suction removes the live actor before the appraisal/arrival

            # interaction reports its check. Require the real observer below;

            # an absent actor alone is neither success nor immediate failure.

            if state.get("movie_state"):client.press(A)

            else:client.input(frames=30)

            continue

        trace.append(dict(retrace=state["retrace"],target=target,pikis=len(state["pikis"])))

        if target.get("picked"):

            client.input(frames=120)

            continue

        live_scene(client)

        walk_to(client,target["position"],radius=75,timeout=30)

        aim_at(client,target["position"],radius=15)

        # Twelve-frame hold plus release admits the real throw animation/cooldown.

        # Never whistle after carriers attach; that would cancel normal transport.

        for _ in range(8):client.press(A,frames=12)

        client.input(frames=120)

    raise TimeoutError(f"physical location {location} carry unfinished: {trace[-5:]}")





def carry_courage(client, timeout=900):

    """Complete the authored day-one route using normal controller actions."""

    # Legacy callback-oriented orchestrators supplied 300 seconds. This route

    # includes real reproduction, tutorials, both captains and authored ramps.

    timeout=max(900,timeout)

    before=live_scene(client)

    raised=raise_day1_squad(client,timeout=max(300,timeout-180))

    movement=follow_waypoints(client,[[-1000,6,2800],[-1427,30,2983],[-1342,38,3205],[-1200,55,3325]],radius=30)

    delivery=carry_location(client,1,timeout=600)

    return dict(state=delivery["state"],trace=delivery["trace"],movement=movement,

                raised_pikis=len(raised["state"]["pikis"]),initial_retrace=before["retrace"],shortcuts=[])





def finish_day_and_save(client, timeout=180):

    """Advance existing recovery/results UI and choose normal Save, then world map.



    Call only after the actual first treasure delivery. Success requires the

    production MemoryCard callback, not presence of a file or a save-menu click.

    """

    initial = client.wait_state(lambda s: True)

    saves = initial.get("card_saves", 0)

    trace = []

    deadline = time.monotonic() + timeout

    while time.monotonic() < deadline:

        state = client.wait_state(lambda s: True)

        trace.append({k:state.get(k) for k in ("game_state","day","movie","save_menu","card_saves","card_serial","native_save_count")})

        if state.get("card_saves", 0)>saves and state.get("game_state")==1:

            return dict(state=state, trace=trace, shortcuts=[])

        menu=state.get("save_menu",{})

        if menu.get("state")==8:

            raise RuntimeError(f"native card error during ordinary save: {menu}")

        if menu.get("state")==1 and menu.get("screen_state")==2:

            if not menu.get("selected_option"):

                client.input(stick_y=90, frames=4)

                client.input(frames=4)

            client.press(A)

        elif state.get("game_state") in (5,7,9) or menu.get("state",0)>0 or state.get("movie_state"):

            client.press(A)

            if state.get("movie_pause"):

                client.press(START)

        elif state.get("game_state")==3 and state.get("paused"):

            # As in landing, a late movie-skip may have opened normal Radar.

            client.press(START)

        elif state.get("game_state")==1:

            if state.get("card_saves",0)<=saves:

                raise RuntimeError("world map reached without an observed native successful save")

        else:

            client.input(frames=20)

        time.sleep(.1)

    raise TimeoutError(f"ordinary day-end/card/world-map route unfinished: {trace[-12:]}")





if __name__ == "__main__":

    parser = argparse.ArgumentParser(description=__doc__)

    for name in ("native", "assets-parent", "profile", "control-dir", "save-dir", "log"):

        parser.add_argument("--"+name, required=True, type=Path)

    parser.add_argument("--carry", action="store_true")

    args = parser.parse_args()

    client = GameplayClient(args.native, args.assets_parent, args.profile, args.control_dir, args.save_dir, args.log)

    try:

        client.start()

        entry = boot_day1(client)

        print(json.dumps(entry))

        if args.carry:

            print(json.dumps(carry_courage(client)))

    finally:

        client.shutdown()

