#!/usr/bin/env python3
"""依頼 301: 場所1 の 1.3 倍の道 (ideal_path_300_place1_x1.3) から, 運ぶ所と戻る所だけを詰めた道を 2 本作る. アームは動かさない.

詰めるのは段階の印 (キー姿勢) の間の 2 区間だけ:
  運ぶ  LIFT (持ち上げ) → ABOVE_BOX (箱の上)
  戻る  RELEASED (離した) → HOME_END (戻った)
を, carry1.5 は両方 1.5 秒 (45 コマ), carry1.0 は両方 1.0 秒 (30 コマ) にする. ほかのコマ (つかむ・離すまわり・始めの止まり・
尻の止まり) は x1.3 のコマをそのまま使う.
区間の中は一律に縮めず, 区間の両端の姿勢 (x1.3 の道のキー姿勢のコマの値) を最小躍度 (5 次式. 端で速さ・加速度 0) で
つなぎ直す (ゆっくり出てゆっくり止まる). x1.3 の道でもこの 2 区間はもとは 298 の最小躍度だが, 依頼 300 の止まりの詰めと
取り直しでキー姿勢のコマが前後に少しずれているため, 同じコマ数でつなぎ直した形とは関節で最大 4° ほど違う (端の姿勢は同じ).
1 コマの変化が関節 10°・爪 20 (lerobot_safe_259 の B) と安全範囲 (お手本 50 本の幅 ±10) に収まらなければ,
収まるまで 1 コマずつ延ばし, その秒数を summary_301.json と画面に出す.

読むだけ: lab/so101_Log11/ideal_paths/ideal_path_300_place1_x1.3.json と お手本 raw_episodes (安全範囲).
書くのは --out の下の新しいファイルだけ (同じ名前があれば止める. Log11 には書かない):
  ideal_path_301_place1_carry1.5.json / .csv, ideal_path_301_place1_carry1.0.json / .csv,
  phases_301.md (3 本の段階ごとの秒数の表), overlay_301_place1.png (関節ごとに 3 本を重ねた図), summary_301.json

  /opt/homebrew/Caskroom/miniforge/base/envs/lerobot/bin/python so101/ideal_paths/make_ideal_paths_301.py
"""
import argparse
import json
import sys
from datetime import datetime
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(HERE.parent))
from make_ideal_paths_296 import MOTORS, URDF, load_urdf_chain, min_jerk  # noqa: E402
from make_ideal_paths_300 import STEP_LIMIT_DEG, STEP_LIMIT_GRIP, steps, write_new, write_path  # noqa: E402

SRC = Path("/Volumes/KIOXIA/r2r2r-data/lab/so101_Log11/ideal_paths/ideal_path_300_place1_x1.3.json")
OUT = Path("/Volumes/KIOXIA/r2r2r-data/lab/so101_Log12/ideal_paths")
FPS = 30
SEGS = (("carry", "LIFT", "ABOVE_BOX"), ("return", "RELEASED", "HOME_END"))     # (名前, 始めの印, 終わりの印)
TARGETS = (1.5, 1.0)                                                            # 運ぶ・戻るの秒数 (両方同じ)


def retime_segments(doc, path, seconds, lo, hi):
    """→ 新しい道, キー姿勢のコマ (名前 → コマ), 区間ごとのコマ数 (延ばしたときはその数)"""
    kf = {k["name"]: k["frame"] for k in doc["keyframes"]}
    order = [k["name"] for k in doc["keyframes"]]
    cuts = sorted((kf[a], kf[b], name) for name, a, b in SEGS)
    n_new = {}
    for name, a, b in SEGS:
        n = int(round(seconds * FPS))
        while True:         # 収まらなければ 1 コマずつ延ばす
            seg = min_jerk(path[kf[a]], path[kf[b]], n)
            x = np.vstack([path[kf[a]][None], seg])
            sj, sg = steps(x)
            if sj <= STEP_LIMIT_DEG and sg <= STEP_LIMIT_GRIP and ((seg >= lo) & (seg <= hi)).all():
                break
            n += 1
            if n > kf[b] - kf[a]:
                raise SystemExit(f"[ABORT] {name}: x1.3 のコマ数でも収まらない")
        n_new[name] = n
    rows, new_kf, pos = [], {}, 0
    prev = 0
    for fa, fb, name in cuts:
        rows.append(path[prev:fa + 1])
        pos += fa + 1 - prev
        rows.append(min_jerk(path[fa], path[fb], n_new[name]))
        pos += n_new[name]
        prev = fb + 1
    rows.append(path[prev:])
    new = np.concatenate(rows, 0)
    shift = lambda f: f - sum(fb - fa - n_new[nm] for fa, fb, nm in cuts if fb <= f)   # noqa: E731
    for nm in order:
        new_kf[nm] = shift(kf[nm])
    for name, a, b in SEGS:         # 区間の端はもとの姿勢のまま
        assert np.allclose(new[new_kf[a]], path[kf[a]]) and np.allclose(new[new_kf[b]], path[kf[b]]), name
    return new, new_kf, n_new


def phase_list(doc, kf_old, kf_new, n):
    ph = []
    for p in doc["phases"]:
        q = dict(p)
        for side in ("start", "end"):
            f = p[side]
            # 段階の境目はキー姿勢のコマ (+1) なので, 印のコマから写す
            m = [nm for nm, fr in kf_old.items() if fr == f or fr + 1 == f]
            if f == 0:
                q[side] = 0
            elif side == "end" and f == len(doc["path"]) - 1:
                q[side] = n - 1
            else:
                nm = next(nm for nm in m if (kf_old[nm] == f if side == "end" else kf_old[nm] + 1 == f))
                q[side] = kf_new[nm] + (0 if side == "end" else 1)
        ph.append(q)
    for a, b in zip(ph, ph[1:]):
        assert b["start"] == a["end"] + 1, (a, b)
    return ph


def boundary_jump(x, frames):
    """境目のコマの前後で, 1 コマの変化 (速さ) がどれだけ変わるか (関節 5 つの最大. 2 階差分の |最大|)"""
    acc = np.abs(np.diff(x[:, :5], n=2, axis=0)).max(1)     # acc[i]: コマ i, i+1, i+2
    return {str(f): round(float(acc[max(f - 2, 0):f + 1].max()), 3) for f in frames}


def phase_seconds(ph):
    return {p["name"]: round((p["end"] - p["start"] + 1) / FPS, 2) for p in ph}


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--src", default=str(SRC))
    ap.add_argument("--out", default=str(OUT))
    ap.add_argument("--urdf", default=str(URDF))
    args = ap.parse_args()
    out = Path(args.out)
    if "so101_Log11" in str(out):
        sys.exit(f"[ABORT] Log11 には書かない: {out}")
    out.mkdir(parents=True, exist_ok=True)
    doc = json.loads(Path(args.src).read_text())
    if doc.get("name") != "ideal_path_300_place1_x1.3" or doc.get("place") != 1 or doc.get("fps") != FPS:
        sys.exit(f"[ABORT] 元の道が違う: {doc.get('name')}")
    path = np.array(doc["path"], np.float64)
    chain = load_urdf_chain(args.urdf)
    import run_so101_policy as R
    lo, hi, n_eps = R.load_safe_range(R.DEFAULT_RAW)
    kf_old = {k["name"]: k["frame"] for k in doc["keyframes"]}
    acc_all = np.abs(np.diff(path[:, :5], n=2, axis=0)).max(1)
    sj0, sg0 = steps(path)
    summary = {"request": 301, "made_at": datetime.now().isoformat(timespec="seconds"), "src": str(args.src),
               "rule": "運ぶ (LIFT→ABOVE_BOX)・戻る (RELEASED→HOME_END) の 2 区間だけ, 両端の姿勢を最小躍度でつなぎ直す. ほかは x1.3 のまま",
               "limits": {"step_joint_deg": STEP_LIMIT_DEG, "step_gripper": STEP_LIMIT_GRIP,
                          "safe_range": f"お手本 {n_eps} 本の幅 ±{R.RANGE_MARGIN:g}"},
               "paths": {"ideal_path_300_place1_x1.3": {
                   "frames": len(path), "seconds": round(len(path) / FPS, 2), "phase_s": phase_seconds(doc["phases"]),
                   "segment_s": {nm: round((kf_old[b] - kf_old[a]) / FPS, 2) for nm, a, b in SEGS},
                   "step_max_joint_deg": round(sj0, 2), "step_max_gripper": round(sg0, 2),
                   "accel_max_deg": round(float(acc_all.max()), 3)}}}
    made = {"ideal_path_300_place1_x1.3": (path, kf_old)}
    for sec in TARGETS:
        name = f"ideal_path_301_place1_carry{sec}"
        new, kf_new, n_new = retime_segments(doc, path, sec, lo, hi)
        ph = phase_list(doc, kf_old, kf_new, len(new))
        kf = [{**k, "frame": int(kf_new[k["name"]])} for k in doc["keyframes"]]
        sj, sg = steps(new)
        ok_range = bool(((new >= lo) & (new <= hi)).all())
        if not (sj <= STEP_LIMIT_DEG and sg <= STEP_LIMIT_GRIP and ok_range):
            raise SystemExit(f"[ABORT] {name}: 1 コマの変化 {sj:.2f}°/{sg:.2f} 安全範囲 {ok_range}")
        bounds = sorted({kf_new[a] for _, a, _ in SEGS} | {kf_new[b] for _, _, b in SEGS})
        acc = np.abs(np.diff(new[:, :5], n=2, axis=0)).max(1)
        st = {"frames": len(new), "seconds": round(len(new) / FPS, 2), "phase_s": phase_seconds(ph),
              "segment_s": {nm: round(n_new[nm] / FPS, 2) for nm, _, _ in SEGS},
              "segment_frames": n_new, "lengthened": {nm: n_new[nm] for nm in n_new if n_new[nm] != int(round(sec * FPS))},
              "step_max_joint_deg": round(sj, 2), "step_max_gripper": round(sg, 2), "safe_range_ok": ok_range,
              "safe_margin_min": round(float(min((new - lo).min(), (hi - new).min())), 2),
              "accel_max_deg": round(float(acc.max()), 3),
              "boundary_accel_deg": boundary_jump(new, bounds)}
        extra = {"request": 301, "made_from": "ideal_path_300_place1_x1.3.json", "speed": doc.get("speed", 1.3),
                 "carry_s": sec, "return_s": sec,
                 "change": f"運ぶ (LIFT→ABOVE_BOX)・戻る (RELEASED→HOME_END) を {sec} 秒の最小躍度でつなぎ直した. ほかは x1.3 のまま"}
        write_path(out, name, doc, new, kf, ph, chain, extra)      # extra の request 301 が 300 より後に入る
        summary["paths"][name] = st
        made[name] = (new, kf_new)
        print(f"[301] {name}: {len(path)} → {len(new)} コマ ({st['seconds']} 秒). 運ぶ {st['segment_s']['carry']} 秒・"
              f"戻る {st['segment_s']['return']} 秒. 1 コマの変化 最大 {st['step_max_joint_deg']}° / 爪 {st['step_max_gripper']}. "
              f"安全範囲 {ok_range} (余り {st['safe_margin_min']}). 延ばした {st['lengthened'] or 'なし'}")

    # 段階ごとの秒数の表
    names = list(made)
    phases = [p["name"] for p in doc["phases"]]
    ja = {p["name"]: p["name_ja"] for p in doc["phases"]}
    lines = ["# 依頼 301 場所1 の 3 本の段階ごとの秒数", "",
             "| 段階 | " + " | ".join(n.replace("ideal_path_", "") for n in names) + " |",
             "|---|" + "---|" * len(names)]
    for p in phases:
        lines.append(f"| {ja[p]} ({p}) | " + " | ".join(f"{summary['paths'][n]['phase_s'][p]:.2f}" for n in names) + " |")
    lines.append("| 合計 | " + " | ".join(f"{summary['paths'][n]['seconds']:.2f}" for n in names) + " |")
    lines += ["", "印の間 (詰めた区間)", "",
              "| 区間 | " + " | ".join(n.replace("ideal_path_", "") for n in names) + " |", "|---|" + "---|" * len(names)]
    for nm, a, b in SEGS:
        lines.append(f"| {nm} ({a}→{b}) | " + " | ".join(f"{summary['paths'][n]['segment_s'][nm]:.2f}" for n in names) + " |")
    lines.append("| 1 コマの変化 最大 (関節°/爪) | " + " | ".join(
        f"{summary['paths'][n]['step_max_joint_deg']} / {summary['paths'][n]['step_max_gripper']}" for n in names) + " |")
    lines.append("")
    write_new(out / "phases_301.md", "\n".join(lines) + "\n")

    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    colors = {names[0]: "#30638e", names[1]: "#edae49", names[2]: "#d1495b"}
    fig, axes = plt.subplots(6, 1, figsize=(12, 15), sharex=True)
    for n in names:
        x, kfn = made[n]
        for j, ax in enumerate(axes):
            ax.plot(np.arange(len(x)) / FPS, x[:, j], color=colors[n], lw=1.8, label=n.replace("ideal_path_", ""))
            for nm in ("LIFT", "ABOVE_BOX", "RELEASED", "HOME_END"):
                ax.axvline(kfn[nm] / FPS, color=colors[n], lw=0.6, ls="--", alpha=0.5)
    for j, ax in enumerate(axes):
        ax.axhline(lo[j], color="#444", ls=":", lw=0.8)
        ax.axhline(hi[j], color="#444", ls=":", lw=0.8)
        ax.set_ylabel(MOTORS[j] + (" (0-100)" if j == 5 else " (deg)"), fontsize=9)
        ax.grid(alpha=0.25)
    axes[0].legend(fontsize=8, loc="upper right")
    axes[-1].set_xlabel("time (s)   dashed = LIFT / ABOVE_BOX / RELEASED / HOME_END of each path")
    fig.suptitle("Request 301  place 1: x1.3 vs carry/return 1.5 s vs 1.0 s   dotted = safe range", y=0.995, fontsize=11)
    fig.tight_layout()
    p_png = out / "overlay_301_place1.png"
    if p_png.exists():
        sys.exit(f"[ABORT] 同じ名前のファイルがある: {p_png}")
    fig.savefig(p_png, dpi=110)
    plt.close(fig)
    write_new(out / "summary_301.json", json.dumps(summary, ensure_ascii=False, indent=1))
    print("\n".join(lines))
    return 0


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