"""依頼 268: SO-101 のテレオペの「ふつう」「速く」だけを実機でやり直す (エイイチ立ち会い).

check_267/run_267.py を元にした (run_267.py は書き換えない). 入口は so101/lerobot_safe_259.py の main()
(このプロセスの中で teleoperate を呼ぶ). 包まない lerobot のコマンドは使わない.
run_267.py から変えたこと:
  - 段ごとに止める. 「次は ふつう (速く). スペースで 15秒 始める」を出し, スペースで始める.
    15秒の間は段の名前と残り秒を大きく出す. 15秒たったら「ふつう 終わり」を出して次の合図を待つ (勝手に次へ進まない)
  - 段の速さを一言で出す (ふつう = ふだん物を取りに行く速さ, 速く = できるだけ速く大きく振る)
  - 終わりの画面で「爪を閉じる・腕を机の上まで下ろしてたたむ」を先に出す
  - 休みの姿勢の待ちの画面 (lerobot_safe_259 の BigTextUI.show) を包み, 幅の外の関節名とずれを大きく出す
    (lerobot_safe_259.py は書き換えない. 待ちの判定・力を抜く条件はそのまま. 絵だけ変える)
  - 問いは見た物で答える形 (はい = y / いいえ = n)
  - 毎コマ, 送った目標と同じ周の今の位置も残す (目標 − 今の位置 を段ごとに出すため)
確認や停止の条件は足していない. q キー = Ctrl-C (run_267 と同じ).

使い方 (conda の lerobot 環境で):  python so101/check_268/run_268.py [--dry]
  --dry: アームにつながず, 画面だけ出す (手順の文を確かめる)
"""

import argparse
import json
import os
import re
import signal
import subprocess
import sys
import time
from pathlib import Path

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
sys.path.insert(0, str(SO101))
PY = sys.executable
FONT = "/System/Library/Fonts/ヒラギノ角ゴシック W6.ttc"
WIN = "依頼268 手順"
W, H = 1440, 860
RAW2DEG = 360.0 / 4096
TELEOP = ["--fps=30"]
STAGES = [("ふつう", 15.0, "ふだん物を取りに行く速さ"), ("速く", 15.0, "できるだけ速く大きく振る")]
PROMPT_TIMEOUT_S = 20 * 60  # 手順の前の待ち (アームは動いていない). 過ぎたら終える
MOTORS = ["shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper"]
JA = {"shoulder_pan": "肩の左右", "shoulder_lift": "肩の上げ下げ", "elbow_flex": "ひじ",
      "wrist_flex": "手首の曲げ", "wrist_roll": "手首のひねり", "gripper": "爪"}
# 依頼258 の速くの段のリーダーの1コマの最大 (check_260/REPORT.md 2節)
REF_258_FAST = {"shoulder_pan": 8.09, "shoulder_lift": 5.54, "elbow_flex": 6.42, "wrist_flex": 7.38,
                "wrist_roll": 3.08, "gripper": 0.08}

EVENTS = HERE / "events_268.jsonl"


def now():
    return time.strftime("%H:%M:%S")


def ev(kind, **kw):
    row = {"t": time.time(), "clock": now(), "kind": kind, **kw}
    with EVENTS.open("a") as fh:
        fh.write(json.dumps(row, ensure_ascii=False, default=str) + "\n")
    print(f"[268] {row['clock']} {kind} {json.dumps(kw, ensure_ascii=False, default=str)[:400]}", flush=True)


# ---- 画面 -------------------------------------------------------------------------------------

class Screen:
    def __init__(self):
        import cv2
        from PIL import ImageFont
        self.cv2 = cv2
        self.f_big = ImageFont.truetype(FONT, 96)
        self.f_mid = ImageFont.truetype(FONT, 50)
        cv2.namedWindow(WIN, cv2.WINDOW_NORMAL)
        cv2.resizeWindow(WIN, W, H)
        cv2.moveWindow(WIN, 30, 30)
        self._key = None
        self._img = None

    def render(self, title, lines, color=(0, 220, 255), log=True):
        key = (title, tuple(lines), color)
        if key != self._key:
            import numpy as np
            from PIL import Image, ImageDraw
            img = Image.new("RGB", (W, H), (0, 0, 0))
            d = ImageDraw.Draw(img)
            d.text((50, 40), title, font=self.f_big, fill=color)
            for i, ln in enumerate(lines):
                d.text((50, 200 + 72 * i), ln, font=self.f_mid, fill=(255, 255, 255))
            self._img = self.cv2.cvtColor(np.asarray(img), self.cv2.COLOR_RGB2BGR)
            self._key = key
            if log:
                ev("screen", title=title, lines=lines)
        self.cv2.imshow(WIN, self._img)

    def poll(self, ms=1):
        return self.cv2.waitKey(ms) & 0xFF

    def ask(self, title, lines, keys, color=(0, 220, 255), timeout=None):
        """keys (文字) のどれかが押されるまで待つ. 押された文字を返す. timeout を過ぎたら None."""
        t0 = time.time()
        self.render(title, lines, color)
        while True:
            k = self.poll(50)
            if k != 255 and chr(k) in keys:
                ev("key", title=title, key=chr(k))
                return chr(k)
            if timeout is not None and time.time() - t0 > timeout:
                ev("timeout", title=title)
                return None
            self.render(title, lines, color, log=False)

    def space(self, title, lines, color=(0, 220, 255), timeout=PROMPT_TIMEOUT_S):
        return self.ask(title, lines + ["", "準備ができたら スペース"], " ", color, timeout) == " "

    def yn(self, question, extra=()):
        """見た物で答える問い. はい = y, いいえ = n."""
        k = self.ask("見た物で答える  y / n", [question, *extra, "", "はい = y     いいえ = n"], "yn",
                     timeout=PROMPT_TIMEOUT_S)
        return None if k is None else k == "y"


# ---- 実行中の記録 -----------------------------------------------------------------------------

class Run:
    """1回の lerobot_safe_259.main() の記録と, 毎コマの画面."""

    def __init__(self, name, screen, on_frame=None):
        self.name, self.screen, self.on_frame = name, screen, on_frame
        self.frames = []       # step_limit の呼ばれ方 (毎コマ)
        self.obs = []          # get_observation の結果
        self.a_reads = []      # A の前後の読み
        self.torque_on = []    # 力が入った直後 0.5秒の今の位置
        self.gate = []         # rest_gate・_auto_return の出入り
        self.big_text = []     # lerobot_safe_259 のウィンドウに出た字 (変わったときだけ)
        self.rest_checks = []
        self.torque_kept = False
        self.in_gate = False
        self.label = "start"
        self.t0 = time.perf_counter()
        self.stop_sent = False

    def sigint(self, why):
        ev("sigint", run=self.name, why=why)
        self.stop_sent = True
        os.kill(os.getpid(), signal.SIGINT)

    def save(self):
        out = HERE / f"{self.name}.json"
        out.write_text(json.dumps({k: v for k, v in vars(self).items()
                                   if k not in ("screen", "on_frame")}, ensure_ascii=False, indent=1, default=str))
        return out


CUR = {"run": None}


def install_hooks():
    import lerobot_safe_259 as ls
    from lerobot.robots.so_follower.so_follower import SOFollower

    orig_step = ls.step_limit

    def step_limit(goal, last, limit=ls.STEP_LIMIT):
        out = orig_step(goal, last, limit)
        r = CUR["run"]
        if r is not None:
            g = {m: float(v) for m, v in goal.items()}
            cut = {m: (round(g[m], 2), round(out[m], 2)) for m in g if abs(out[m] - g[m]) > 1e-6}
            r.frames.append({"t": time.perf_counter() - r.t0, "label": r.label, "gate": r.in_gate,
                             "goal": {m: round(v, 2) for m, v in g.items()},
                             "last": {m: round(float(last[m]), 2) for m in g},
                             "sent": {m: round(float(out[m]), 2) for m in g},
                             "present": ({m: r.obs[-1].get(f"{m}.pos") for m in g} if r.obs else None),
                             "cut": cut})
            if r.on_frame is not None and not r.in_gate:
                r.on_frame(r)
        return out

    ls.step_limit = step_limit

    orig_hold = ls.hold_goal_at_present

    def hold_goal_at_present(bus, motors=None, retry=ls.A_RETRY):
        r = CUR["run"]
        pre = {}
        if r is not None:
            try:  # 読むだけ (A の前に Goal が何を指していたか = A がなければ力が入る瞬間に向かった先)
                pre["goal"] = bus.sync_read("Goal_Position", motors, normalize=False, num_retry=2)
                pre["present"] = bus.sync_read("Present_Position", motors, normalize=False, num_retry=2)
            except Exception as e:
                pre["error"] = repr(e)
        raw = orig_hold(bus, motors, retry)
        if r is not None:
            row = {"port": bus.port, "t": time.perf_counter() - r.t0, "written": dict(raw), **pre}
            if "goal" in pre:
                row["goal_minus_present_deg"] = {m: round((int(pre["goal"][m]) - int(pre["present"][m])) * RAW2DEG, 2)
                                                 for m in pre["goal"]}
            r.a_reads.append(row)
        return raw

    ls.hold_goal_at_present = hold_goal_at_present

    orig_guard = ls.guard_bus

    def guard_bus(bus, role, on_connect, on_before_torque=None, lock=None):
        orig_guard(bus, role, on_connect, on_before_torque, lock)
        if role != "follower" or getattr(bus, "_p268", False):
            return
        enable = bus.enable_torque

        def enable_torque(motors=None, num_retry=0):
            enable(motors, num_retry=num_retry)
            r = CUR["run"]
            if r is None:
                return
            fa = [a for a in r.a_reads if a["port"] == bus.port]
            base = fa[-1]["written"] if fa else None
            t_on = time.perf_counter()
            samples = []
            while time.perf_counter() - t_on < 0.5:  # 力が入った直後 0.5秒の今の位置 (読むだけ)
                try:
                    p = bus.sync_read("Present_Position", motors, normalize=False, num_retry=2)
                    samples.append({"dt": round(time.perf_counter() - t_on, 3), **{m: int(v) for m, v in p.items()}})
                except Exception as e:
                    samples.append({"error": repr(e)})
                time.sleep(0.02)
            mx = {}
            if base:
                for m in base:
                    vals = [s[m] for s in samples if m in s]
                    if vals:
                        mx[m] = round(max(abs(v - int(base[m])) for v in vals) * RAW2DEG, 2)
            r.torque_on.append({"t": t_on - r.t0, "base": dict(base or {}), "max_diff_deg": mx, "samples": samples})
            ev("torque_on", run=r.name, max_diff_deg=mx)

        bus.enable_torque = enable_torque
        bus._p268 = True

    ls.guard_bus = guard_bus

    orig_gate = ls.rest_gate

    def rest_gate(follower, leader=None, **kw):
        r = CUR["run"]
        t = time.perf_counter()
        if r is not None:
            r.in_gate = True
            r.gate.append({"what": "rest_gate_start", "t": t - r.t0, "leader": leader is not None})
        try:
            res = orig_gate(follower, leader, **kw)
            if r is not None:
                r.gate.append({"what": "rest_gate_end", "t": time.perf_counter() - r.t0, "result": res,
                               "dur_s": round(time.perf_counter() - t, 2)})
            return res
        except BaseException as e:
            if r is not None:
                r.gate.append({"what": "rest_gate_exc", "t": time.perf_counter() - r.t0, "exc": repr(e),
                               "dur_s": round(time.perf_counter() - t, 2)})
            raise
        finally:
            if r is not None:
                r.in_gate = False

    ls.rest_gate = rest_gate

    orig_auto = ls._auto_return

    def _auto_return(follower, ui, center, tol, sleep):
        r = CUR["run"]
        t = time.perf_counter()
        res = orig_auto(follower, ui, center, tol, sleep)
        if r is not None:
            r.gate.append({"what": "auto_return", "t": t - r.t0, "result": res,
                           "dur_s": round(time.perf_counter() - t, 2)})
        return res

    ls._auto_return = _auto_return

    orig_rc = ls.rest_check

    def rest_check(pos, center, tol):
        ok, diff = orig_rc(pos, center, tol)
        r = CUR["run"]
        if r is not None and r.in_gate:
            r.rest_checks.append({"t": round(time.perf_counter() - r.t0, 3), "ok": ok,
                                  "diff": {m: round(v, 2) for m, v in diff.items()}})
        return ok, diff

    ls.rest_check = rest_check

    orig_close = ls.close_without_torque_off

    def close_without_torque_off(follower):
        r = CUR["run"]
        if r is not None:
            r.torque_kept = True
            ev("torque_kept_port_closed", run=r.name)
        return orig_close(follower)

    ls.close_without_torque_off = close_without_torque_off

    orig_show, orig_key = ls.BigTextUI.show, ls.BigTextUI.key

    def show(self, title, lines, color=(0, 200, 255)):
        r = CUR["run"]
        if r is not None and (not r.big_text or r.big_text[-1]["title"] != title):
            r.big_text.append({"t": time.perf_counter() - r.t0, "title": title, "lines": list(lines)})
            ev("lerobot_safe_window", run=r.name, title=title)
        if r is not None and r.in_gate and getattr(self, "cv2", None) is not None and r.rest_checks:
            return show_rest_big(self, title, lines, color, r)
        return orig_show(self, title, lines, color)

    def key(self, ms=1):
        k = orig_key(self, ms)
        r = CUR["run"]
        if r is not None and k in (ord("q"), 27):
            r.sigint("q (lerobot_safe のウィンドウ)")
        return k

    ls.BigTextUI.show, ls.BigTextUI.key = show, key

    orig_obs = SOFollower.get_observation

    def get_observation(self):
        obs = orig_obs(self)
        r = CUR["run"]
        if r is not None:
            r.obs.append({"t": round(time.perf_counter() - r.t0, 3), "label": r.label,
                          **{k: round(float(v), 2) for k, v in obs.items() if k.endswith(".pos")}})
        return obs

    SOFollower.get_observation = get_observation
    return ls


def run_safe(ls, name, argv, screen, on_frame=None):
    r = Run(name, screen, on_frame)
    CUR["run"] = r
    ev("run_start", run=name, argv=argv)
    result = {"name": name, "exc": None}
    try:
        result["ret"] = ls.main(argv)
    except KeyboardInterrupt:
        result["exc"] = "KeyboardInterrupt"
    except BaseException as e:  # 通信が返らない など
        result["exc"] = repr(e)
    finally:
        CUR["run"] = None
        try:
            screen.cv2.destroyWindow(ls.WIN)
        except Exception:
            pass
    result["torque_kept"] = r.torque_kept
    result["file"] = str(r.save())
    ev("run_end", **result)
    return r, result


# ---- 読むだけで力の状態を見る ---------------------------------------------------------------

def torque_all_zero():
    p = subprocess.run([PY, str(SO101 / "read_servos_248.py")], capture_output=True, text=True, timeout=60)
    text = p.stdout
    (HERE / "read_servos_last.txt").write_text(text)
    blocks = {}
    port = None
    for ln in text.splitlines():
        if ln.startswith("== "):
            port = ln[3:].strip()
            blocks[port] = []
        m = re.match(r"^\s+(\d)\s+777\s+\S+\s+(\d+)\s+\S+\s+\d+\s+(\d)\s+\d", ln)
        if m and port:
            blocks[port].append((int(m.group(1)), int(m.group(2)), int(m.group(3))))
    fol = blocks.get("/dev/tty.usbmodem5CBC4321631", [])
    ok = len(fol) == 6 and all(t == 0 for _, _, t in fol)
    ev("read_servos", follower=fol, leader=blocks.get("/dev/tty.usbmodem5CBC4323581", []), ok=ok)
    return ok, fol




# ---- 休みの姿勢の待ちの絵 (lerobot_safe_259 の BigTextUI.show を包む) ---------------------------

_REST_FONTS = {}


def show_rest_big(ui, title, lines, color, r):
    """幅の外の関節名とずれを大きく出す. 値は rest_check の記録 (lerobot_safe_259 の判定そのもの) から取る."""
    import numpy as np
    from PIL import Image, ImageDraw, ImageFont
    import lerobot_safe_259 as ls
    if not _REST_FONTS:
        _REST_FONTS.update(big=ImageFont.truetype(FONT, 64), huge=ImageFont.truetype(FONT, 76),
                           mid=ImageFont.truetype(FONT, 34))
    _, tol = ls.load_rest_pose()
    diff = r.rest_checks[-1]["diff"]
    out = [m for m in MOTORS if abs(diff[m]) > tol[m]]
    img = Image.new("RGB", (1280, 720), (0, 0, 0))
    d = ImageDraw.Draw(img)
    d.text((40, 30), title, font=_REST_FONTS["big"], fill=color)
    y = 130
    if out:
        d.text((40, y), "幅の外 (ここを戻す):", font=_REST_FONTS["mid"], fill=(255, 255, 255))
        y += 50
        for m in out[:4]:
            d.text((40, y), f"{JA[m]}  {diff[m]:+.0f}°  (幅 {tol[m]:.0f})", font=_REST_FONTS["huge"],
                   fill=(60, 60, 255))
            y += 100
    else:
        d.text((40, y + 40), "全部 幅の中. そのまま止める", font=_REST_FONTS["huge"], fill=(80, 255, 80))
        y += 200
    y = max(y + 10, 560)
    d.text((40, y), "爪を閉じる・腕を机の上まで下ろしてたたむ", font=_REST_FONTS["mid"], fill=(255, 255, 255))
    for i, ln in enumerate(lines[-2:]):
        d.text((40, y + 45 + 40 * i), ln, font=_REST_FONTS["mid"], fill=(180, 180, 180))
    ui.cv2.imshow(ls.WIN, ui.cv2.cvtColor(np.asarray(img), ui.cv2.COLOR_RGB2BGR))
    try:
        ui.cv2.moveWindow(ls.WIN, 60, 60)
    except Exception:
        pass
    key = tuple(out)
    if getattr(r, "_rest_out_last", None) != key:  # 幅の外の顔ぶれが変わったときだけ記録
        r._rest_out_last = key
        ev("rest_out_joints", run=r.name, out={m: diff[m] for m in out})


# ---- 手順 -----------------------------------------------------------------------------------

RESULTS = {}


def stop_screen(screen):
    """止まった・通信が返らない・力を入れたままポートを閉じた ときの画面."""
    screen.ask("支える → 電源を切る", ["フォロワーを手で支える", "フォロワーの電源を切る",
                                     "", "電源を切ったら スペース"], " ", color=(0, 0, 255), timeout=1800)


def countdown(sc, name, left, desc, idx):
    """15秒の間の画面. 段の名前と残り秒を大きく."""
    import numpy as np
    from PIL import Image, ImageDraw, ImageFont
    if not hasattr(sc, "f_huge"):
        sc.f_huge = ImageFont.truetype(FONT, 230)
    img = Image.new("RGB", (W, H), (0, 0, 0))
    d = ImageDraw.Draw(img)
    d.text((50, 30), f"{name}", font=sc.f_huge, fill=(0, 220, 255))
    d.text((50, 300), f"残り {left:4.1f} 秒", font=sc.f_huge, fill=(255, 255, 255))
    d.text((50, 600), f"{idx} / 2 段目   {name} = {desc}", font=sc.f_mid, fill=(255, 255, 255))
    d.text((50, 690), "(止めたいとき: q)", font=sc.f_mid, fill=(180, 180, 180))
    sc._img = sc.cv2.cvtColor(np.asarray(img), sc.cv2.COLOR_RGB2BGR)
    sc._key = None
    sc.cv2.imshow(WIN, sc._img)


def stage_stats(frames, label):
    """段ごとの: コマ数・切られたコマ数・目標 − 今の位置の最大 (関節ごと)・リーダーの1コマの最大の動き."""
    fs = [f for f in frames if f["label"] == label and not f["gate"]]
    out = {"frames": len(fs), "cut_frames": sum(1 for f in fs if f["cut"]),
           "cut_examples": [f["cut"] for f in fs if f["cut"]][:10]}
    gp = {m: 0.0 for m in MOTORS}
    for f in fs:
        if f.get("present"):
            for m in MOTORS:
                p = f["present"].get(m)
                if p is not None:
                    gp[m] = max(gp[m], abs(f["sent"][m] - p))
    out["sent_minus_present_max"] = {m: round(v, 2) for m, v in gp.items()}
    lead = {m: 0.0 for m in MOTORS}
    for a, b in zip(fs, fs[1:]):
        for m in MOTORS:
            lead[m] = max(lead[m], abs(b["goal"][m] - a["goal"][m]))
    out["leader_step_max"] = {m: round(v, 2) for m, v in lead.items()}
    out["leader_step_max_vs_258_fast"] = {m: f"{lead[m]:.2f} / {REF_258_FAST[m]:.2f}" for m in MOTORS}
    if len(fs) > 1:
        out["hz"] = round((len(fs) - 1) / (fs[-1]["t"] - fs[0]["t"]), 2)
    return out


def step0(screen):
    ok, fol = torque_all_zero()
    RESULTS["0"] = {"torque_zero": ok, "follower": fol}
    if not ok:
        screen.ask("力が入っている (始めない)", ["フォロワーの Torque が 0 ではない", f"{fol}",
                                            "支える → 電源を切る", "", "スペースで終える"], " ",
                   color=(0, 0, 255), timeout=1800)
        return False
    return screen.space("0. 始める前", ["フォロワーのまわりを空ける", "電源をすぐ切れるようにする",
                                       "リーダーとフォロワーの姿勢を近づける",
                                       "次のスペースで つなぐ (力が入る)", "(止めたいとき: q キー = Ctrl-C)"])


def step1(screen, ls):
    st = {"phase": "ready", "t": None, "n": 0, "idx": 0}

    def on_frame(r):
        st["n"] += 1
        sc = r.screen
        k = sc.poll(1)
        if k in (ord("q"), 27) and not r.stop_sent:
            r.sigint("q (手順のウィンドウ)")
            return
        ph = st["phase"]
        t = time.perf_counter()
        if ph in ("ready", "between"):
            i = st["idx"]
            name, dur, desc = STAGES[i]
            r.label = "ready" if i == 0 else f"after_{STAGES[i - 1][0]}"
            head = [] if i == 0 else [f"{STAGES[i - 1][0]} 終わり", ""]
            sc.render(f"次は {name}", head + [f"スペースで {dur:.0f}秒 始める", f"{name} = {desc}",
                                             "(止めたいとき: q)"])
            if k == ord(" "):
                st.update(phase="stage", t=t)
                ev("stage", stage=name)
        elif ph == "stage":
            i = st["idx"]
            name, dur, desc = STAGES[i]
            r.label = name
            left = dur - (t - st["t"])
            if left <= 0:
                ev("stage_end", stage=name)
                if i + 1 < len(STAGES):
                    st.update(phase="between", idx=i + 1)
                else:
                    st.update(phase="end_wait")
                return
            if st["n"] % 3 == 0:
                countdown(sc, name, left, desc, i + 1)
        elif ph == "end_wait":
            r.label = "end_wait"
            sc.render("速く 終わり", ["リーダーで 爪を閉じる",
                                     "腕を机の上まで下ろして たたむ (休みの姿勢)",
                                     "たたんだら スペース (力が抜ける)",
                                     "幅の外だと 赤い字で関節名が出る → そこを戻す"])
            if k == ord(" "):
                st["phase"] = "end"
                r.sigint("終わり (たたんだ)")

    r, res = run_safe(ls, "step1_teleop", ["teleoperate", *TELEOP], screen, on_frame)
    out = {"run": res, "reached": st["phase"]}
    out["stages"] = {name: stage_stats(r.frames, name) for name, _, _ in STAGES}
    out["cut_frames_outside_stages"] = {}
    for f in r.frames:
        if f["cut"] and f["label"] not in [s for s, _, _ in STAGES]:
            key = ("gate:" if f["gate"] else "") + f["label"]
            out["cut_frames_outside_stages"][key] = out["cut_frames_outside_stages"].get(key, 0) + 1
    out["torque_on"] = [x["max_diff_deg"] for x in r.torque_on]
    out["gate"] = r.gate
    waits = [g for g in r.gate if g["what"] in ("rest_gate_end", "rest_gate_exc")]
    # rest_gate は終わりに2回呼ばれる (リーダーで戻す待ち → もう一度見るだけ). 待ちの時間は合計
    out["rest_wait_s"] = round(sum(g["dur_s"] for g in waits), 2) if waits else None
    out["rest_wait_each_s"] = [(g.get("result") or g.get("exc"), g["dur_s"]) for g in waits]
    out["rest_out_seq"] = []  # 幅の外だった関節が何秒続いたか (rest_check の記録から)
    if r.rest_checks:
        _, tol = ls.load_rest_pose()
        prev, t0 = None, r.rest_checks[0]["t"]
        for c in r.rest_checks + [None]:
            cur = None if c is None else tuple(m for m in MOTORS if abs(c["diff"][m]) > tol[m])
            if c is None or cur != prev:
                if prev is not None:
                    out["rest_out_seq"].append({"out": list(prev), "s": round(t_last - t0, 2)})
                if c is not None:
                    prev, t0 = cur, c["t"]
            if c is not None:
                t_last = c["t"]
    RESULTS["1"] = out
    if res["torque_kept"] or res["exc"] not in (None, "KeyboardInterrupt"):
        stop_screen(screen)
        return False
    for key, q in [("yn_normal_follow", "ふつう で, フォロワーは遅れずに リーダーについてきた？"),
                   ("yn_fast_follow", "速く 振っても, フォロワーは遅れずに ついてきた？"),
                   ("yn_no_jump", "力が入った瞬間・動かしている間に, フォロワーが ガクッと飛んだ？"),
                   ("yn_rest_screen", "終わりの待ちで, 赤い字の関節名を見て 戻せた？")]:
        if key == "yn_rest_screen" and not r.rest_checks:
            continue
        out[key] = screen.yn(q)
    return True


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--dry", action="store_true")
    args = ap.parse_args()
    screen = Screen()
    ev("start", dry=args.dry)
    if args.dry:
        screen.space("次は ふつう (dry)", ["スペースで 15秒 始める", "ふつう = " + STAGES[0][2]], timeout=3)
        t0 = time.perf_counter()
        while time.perf_counter() - t0 < 2:
            countdown(screen, "速く", 15 - (time.perf_counter() - t0), STAGES[1][2], 2)
            screen.poll(50)
        return 0
    import lerobot_safe_259 as _  # noqa: F401  (先に読み込んでから包む)
    ls = install_hooks()
    try:
        if not step0(screen):
            return 1
        ok = step1(screen, ls)
        screen.space("おわり", ["手順はすべて終わった", "フォロワーの電源を切ってよい"], timeout=600)
        return 0 if ok else 2
    finally:
        (HERE / "results_268.json").write_text(json.dumps(RESULTS, ensure_ascii=False, indent=1, default=str))
        ev("end")


if __name__ == "__main__":
    sys.exit(main())
