#!/usr/bin/env python3
"""Android OSC 4 proof driver. Run from a checkout after pairing its fresh client.
Usage: driver.py live|replay SESSION OUTPUT_DIRECTORY
Seed each fresh server with a project and a devReplay/multi-turn thread titled Palette replay.
For replay, return the first device lease, lease/install/pair a fresh Pixel 9,
then open that same thread and its Terminal menu before replay. All state comes from the app CLI/UI.
"""
import pathlib, subprocess, sys, time
phase, session, root = sys.argv[1:]
out = pathlib.Path(root) / (phase + "-" + time.strftime("%Y%m%d-%H%M%S"))
out.mkdir(parents=True, exist_ok=False)
def device(*args):
    return subprocess.run(["agent-device", *args, "--session", session], check=True, text=True, capture_output=True).stdout
def press(label):
    print(device("press", 'label="' + label + '"', "--settle"))
def command(text):
    print(device("type", text))
    print(device("keyboard", "enter"))
if phase == "live":
    press("Terminal")
    print(device("press", 'text="Open new terminal"', "--settle"))
    command('export PS1="$ "; clear')
    command(r"printf 'A\033]4;1;?\007B\n'; read -rs -t 2 -d $'\a' x; echo swallowed=${#x}")
    command(r"printf '\033]4;1;#00aa00\007\033[31mPALETTE SETTER RETAINED\033[0m\n'")
    print(device("screenshot", str(out / "live.png")))
elif phase == "replay":
    print(device("record", "start", str(out / "replay.mp4"), "--hide-touches"))
    print(device("press", 'text="Terminal 1"', "--settle"))
    print(device("press", 'label="Dismiss keyboard"', "--settle"))
    print(device("screenshot", str(out / "replayed-a.png")))
    time.sleep(0.5)
    print(device("screenshot", str(out / "replayed-b.png")))
    print(device("record", "stop"))
else:
    raise SystemExit("Expected live or replay")
print(out)
