#!/usr/bin/env python3
"""依頼 302: 学習用の道 ideal_path_300_place{1..5}_x1.3 (場所4 はつかむ所を直した道の x1.3) から,
HOME に戻り終えたあとの止まりを削った道を作る. アームは動かさない.

削るのは HOME_END (戻った) のキー姿勢のコマより後ろだけ. HOME_END のコマ (HOME の姿勢) は 1 コマ残し, 道の最後のコマにする.
戻る動きそのものと, それより前のコマは x1.3 のまま (値も同じ). 削るコマが HOME_END のコマと同じ値でなければ止める.
段階 RETURN (戻る) の終わりを新しい最後のコマにする. ほかの段階・キー姿勢のコマ番号は変わらない.

読むだけ: lab/so101_Log11/ideal_paths/ideal_path_300_place{N}_x1.3.json
書くのは --out の下の新しいファイルだけ (同じ名前があれば止める. Log11 には書かない):
  ideal_path_302_place{N}_x1.3_trim.json / .csv, phases_302.md (段階ごとの秒数 前と後), summary_302.json

  /opt/homebrew/Caskroom/miniforge/base/envs/lerobot/bin/python so101/ideal_paths/make_ideal_paths_302.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 URDF, load_urdf_chain  # 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")
OUT = Path("/Volumes/KIOXIA/r2r2r-data/lab/so101_Log12/ideal_paths")
FPS = 30
PLACES = (1, 2, 3, 4, 5)


def trim_tail(doc):
    """→ 削った道, 段階, 削ったコマ数"""
    path = np.array(doc["path"], np.float64)
    h = {k["name"]: k["frame"] for k in doc["keyframes"]}["HOME_END"]
    if np.abs(path[h:] - path[h]).max() > 0:
        raise SystemExit(f"[ABORT] {doc['name']}: HOME_END より後ろが止まりでない")
    ph = [dict(p) for p in doc["phases"]]
    if ph[-1]["name"] != "RETURN" or not ph[-1]["start"] <= h <= ph[-1]["end"]:
        raise SystemExit(f"[ABORT] {doc['name']}: 最後の段階が RETURN でない")
    ph[-1]["end"] = h
    return path[:h + 1], ph, len(path) - 1 - h


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)
    chain = load_urdf_chain(args.urdf)
    summary = {"request": 302, "made_at": datetime.now().isoformat(timespec="seconds"), "src": str(args.src),
               "rule": "HOME_END より後ろの止まりを削る. HOME_END のコマは 1 コマ残す. それより前は x1.3 のまま", "paths": {}}
    rows = []
    for place in PLACES:
        src_name = f"ideal_path_300_place{place}_x1.3"
        doc = json.loads((Path(args.src) / f"{src_name}.json").read_text())
        if doc.get("name") != src_name or doc.get("place") != place or doc.get("fps") != FPS:
            sys.exit(f"[ABORT] 元の道が違う: {doc.get('name')}")
        new, ph, n_cut = trim_tail(doc)
        name = f"ideal_path_302_place{place}_x1.3_trim"
        sj, sg = steps(new)
        if not (sj <= STEP_LIMIT_DEG and sg <= STEP_LIMIT_GRIP):
            raise SystemExit(f"[ABORT] {name}: 1 コマの変化 {sj:.2f}°/{sg:.2f}")
        extra = {"request": 302, "made_from": f"{src_name}.json", "speed": doc.get("speed", 1.3),
                 "trimmed_tail_frames": n_cut,
                 "change": f"HOME_END より後ろの止まり {n_cut} コマ ({n_cut / FPS:.2f} 秒) を削った. HOME_END のコマを最後に 1 コマ残した. ほかは x1.3 のまま"}
        write_path(out, name, doc, new, doc["keyframes"], ph, chain, extra)
        tcp_same = bool(np.allclose(np.array(json.loads((out / f"{name}.json").read_text())["tcp_m"]),
                                    np.array(doc["tcp_m"])[:len(new)], atol=1e-5))
        before, after = phase_seconds(doc["phases"]), phase_seconds(ph)
        summary["paths"][name] = {"place": place, "src": src_name, "frames_before": len(doc["path"]), "frames_after": len(new),
                                  "seconds_before": round(len(doc["path"]) / FPS, 2), "seconds_after": round(len(new) / FPS, 2),
                                  "trimmed_frames": n_cut, "trimmed_s": round(n_cut / FPS, 2),
                                  "phase_s_before": before, "phase_s_after": after,
                                  "step_max_joint_deg": round(sj, 2), "step_max_gripper": round(sg, 2), "tcp_same_as_src": tcp_same}
        rows.append((place, doc, ph, len(doc["path"]), len(new), n_cut))
        print(f"[302] {name}: {len(doc['path'])} → {len(new)} コマ ({len(doc['path']) / FPS:.2f} → {len(new) / FPS:.2f} 秒). "
              f"削った {n_cut} コマ. 1 コマの変化 最大 {sj:.2f}° / 爪 {sg:.2f}. 手先も元と同じ {tcp_same}")

    phases = [p["name"] for p in rows[0][1]["phases"]]
    ja = {p["name"]: p["name_ja"] for p in rows[0][1]["phases"]}
    head = " | ".join(f"場所{pl} 前 | 場所{pl} 後" for pl, *_ in rows)
    lines = ["# 依頼 302 学習用の道 (x1.3) の段階ごとの秒数 (前 = ideal_path_300_place{N}_x1.3, 後 = ideal_path_302_place{N}_x1.3_trim)", "",
             f"| 段階 | {head} |", "|---|" + "---|" * (2 * len(rows))]
    for p in phases:
        cells = []
        for pl, doc, ph, *_ in rows:
            cells += [f"{phase_seconds(doc['phases'])[p]:.2f}", f"{phase_seconds(ph)[p]:.2f}"]
        lines.append(f"| {ja[p]} ({p}) | " + " | ".join(cells) + " |")
    lines.append("| 合計 | " + " | ".join(f"{nb / FPS:.2f} | {na / FPS:.2f}" for _, _, _, nb, na, _ in rows) + " |")
    lines.append("| コマ数 | " + " | ".join(f"{nb} | {na}" for _, _, _, nb, na, _ in rows) + " |")
    lines += ["", "削ったコマ (HOME_END より後ろの止まり)", "", "| 場所 | 削ったコマ | 秒 |", "|---|---|---|"]
    lines += [f"| {pl} | {nc} | {nc / FPS:.2f} |" for pl, _, _, _, _, nc in rows]
    lines.append("")
    write_new(out / "phases_302.md", "\n".join(lines) + "\n")
    write_new(out / "summary_302.json", json.dumps(summary, ensure_ascii=False, indent=1))
    print("\n".join(lines))
    return 0


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