"""Normal-route wrapper: pinned canonical driver plus elevated Red recruitment.

Only ordinary PAD movement/cursor/whistle input is changed. The base source
must remain byte-identical to the declared SHA256 throughout this test.
"""
import hashlib
import importlib.util
import json
from pathlib import Path

BASE_DRIVER_SHA256 = "2658e2cc77220f3fe516ac121035205f7b37173a0c97afab0d6adfde285f587b"
_candidates = (Path.cwd()/"native/tools/test_gameplay_control.py",
               Path(__file__).with_name("test_gameplay_control.py"))
BASE_DRIVER_PATH = next((p.resolve() for p in _candidates if p.is_file()), None)
if BASE_DRIVER_PATH is None:
    raise RuntimeError("pinned base driver not found; run from the Pikmin2 workspace")
if hashlib.sha256(BASE_DRIVER_PATH.read_bytes()).hexdigest() != BASE_DRIVER_SHA256:
    raise RuntimeError("canonical normal driver differs from pinned2658 source")
if Path(__file__).name == "executed-driver.py":
    # The common orchestrator snapshots this wrapper. Retain its exact base
    # beside it as well, without modifying the frozen native source closure.
    _snapshot = Path(__file__).with_name("executed-base-driver.py")
    _snapshot.write_bytes(BASE_DRIVER_PATH.read_bytes())
    Path(__file__).with_name("base-driver-pin.json").write_text(json.dumps({
        "source":str(BASE_DRIVER_PATH),"sha256":BASE_DRIVER_SHA256,
        "snapshot":str(_snapshot),"boundary":"ordinary PAD only; no actor/reward setters"},indent=2))
_spec = importlib.util.spec_from_file_location("normal_recruit_base", BASE_DRIVER_PATH)
_base = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_base)
globals().update({key:value for key,value in vars(_base).items() if not key.startswith("_")})

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
        candidate=min(candidates,key=lambda p:distance(p["position"],navi["position"]))
        target=candidate["position"];actor_id=candidate["actor_id"]
        # 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)
        current=next(p for p in state["pikis"] if p["actor_id"]==actor_id)
        target=current["position"]
        if target[1]>navi["position"][1]+20:
            # Try the real whistle before walking toward an upper platform.
            # Measure the fresh actor against the actual terrain-conforming
            # cursor, rather than assuming a fixed cliff-edge approach works.
            gap=distance(navi["position"],target);aim=list(target)
            if gap>90:
                for axis in (0,2):
                    aim[axis]=navi["position"][axis]+90*(target[axis]-navi["position"][axis])/gap
            aim_at(client,aim,radius=12)
            observed=live_scene(client)
            current=next(p for p in observed["pikis"] if p["actor_id"]==actor_id)
            cursor=active_navi(observed)["cursor"]
            if math.dist(cursor,current["position"])<=86:
                client.input(frames=8)
                client.input(buttons=B,frames=120)
                client.input(frames=8)
            else:
                walk_to(client,current["position"],radius=160,timeout=40)
            continue
        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)}")

_base.gather_day1_group = gather_day1_group
