#!/usr/bin/env python3
"""build_demo_episodes.py — run_pick_place の記録から π0.5 学習用エピソードを作る (Mac 側・段階1).

入力 (1 試行 = 1 run_stem):
  runs/run_pick_place/{run_stem}/{run_stem}.json      判定 (judgments.pick/place.human_verdict)
  runs/run_pick_place/{run_stem}/recording/states.csv  actual (実測6軸) / gripper_cmd / stage 行
  runs/run_pick_place/{run_stem}/recording/top.mp4 + top_frame_log.csv  上カメラ
  (recorder.py --top と run_pick_place.py --record-demo で記録したもの)

出力 (1 エピソード = 1 フォルダ):
  datasets/{DATASET}/raw_episodes/{run_stem}/
    frames/000000.jpg ...   上カメラ (長辺 IMG_LONG px, 縦横比維持)
    episode.npz             t[N], state[N,7], actions[N,7]   (7 = j0..j5 [deg] + gripper 0/1)
    meta.json
  datasets/{DATASET}/index.json   採用/不採用とその理由

設計:
  - 時間軸は FPS (10Hz) で並べ直す.
  - state: 実測角 (約3Hz) を線形補間. gripper は指令した瞬間で 0→1 / 1→0 に切替.
  - action: 0.1 秒後の state (絶対角). π0.5 は action chunk でこれを予測する.
  - 停止区間 (動き < IDLE_EPS_DEG が IDLE_MAX_SEC 超) は先頭 IDLE_KEEP_SEC だけ残して詰める.
    検出・VLM・人の入力待ちを「待つ動作」として学習させないため.
  - 採用条件: pick と place の人の判定がどちらも yes (既定). VLM 判定は使わない.

Usage:
  python3 pi05/build_demo_episodes.py                # 2026-10-15 以降の全試行
  python3 pi05/build_demo_episodes.py --since 20261020 --dataset mecharm_redblock_box_scripted_v1
  python3 pi05/build_demo_episodes.py --run run_0001_20261015_180000 --force
"""
import argparse
import csv
import json
import shutil
import sys
from pathlib import Path

import cv2
import numpy as np

DATA_ROOT = Path("/Volumes/KIOXIA/r2r2r-data")
RUNS_ROOT = DATA_ROOT / "runs" / "run_pick_place"
DEFAULT_DATASET = "mecharm_redblock_box_scripted_v1"
TASK = "put the red block in the white box"
FPS = 10
IMG_LONG = 384            # 保存画像の長辺 px. openpi 側で 224x224 に resize_with_pad される
JPEG_QUALITY = 95
IDLE_EPS_DEG = 0.3        # 1 ステップでの最大関節変化がこれ未満なら「停止」
IDLE_MAX_SEC = 2.0        # これより長い停止区間は詰める
IDLE_KEEP_SEC = 1.0       # 詰めるときに残す長さ
ANGLE_ABS_MAX = 200.0     # 実測値のサニティ (これを超えたら読み取り異常として捨てる)
MIN_ACTUAL_SAMPLES = 20


def ensure_ssd():
    if not DATA_ROOT.exists():
        sys.exit(f"[ERROR] SSD not mounted: {DATA_ROOT}")


def load_states(path):
    actual_t, actual_q, grip_t, grip_s = [], [], [], []
    with path.open(newline="") as f:
        for row in csv.DictReader(f):
            ev = row.get("event_type")
            try:
                ts = float(row["ts"])
            except Exception:
                continue
            if ev == "actual":
                try:
                    q = [float(row[f"j{i}"]) for i in range(6)]
                except Exception:
                    continue
                if any(abs(v) > ANGLE_ABS_MAX for v in q):
                    continue
                actual_t.append(ts); actual_q.append(q)
            elif ev == "gripper_cmd":
                try:
                    grip_t.append(ts); grip_s.append(1.0 if int(float(row["gripper_state"])) == 1 else 0.0)
                except Exception:
                    pass
    return (np.array(actual_t), np.array(actual_q, dtype=np.float64).reshape(-1, 6),
            np.array(grip_t), np.array(grip_s))


def drop_spikes(t, q, max_jump_deg=40.0):
    """前後どちらとも max_jump_deg 以上離れた孤立点 (読み取り異常) を捨てる."""
    if len(t) < 3:
        return t, q
    keep = np.ones(len(t), dtype=bool)
    for i in range(1, len(t) - 1):
        a = np.max(np.abs(q[i] - q[i - 1])); b = np.max(np.abs(q[i] - q[i + 1]))
        c = np.max(np.abs(q[i + 1] - q[i - 1]))
        if a > max_jump_deg and b > max_jump_deg and c < max_jump_deg:
            keep[i] = False
    return t[keep], q[keep]


def load_frame_log(path):
    idx, ts = [], []
    with path.open(newline="") as f:
        for row in csv.DictReader(f):
            idx.append(int(row["frame_idx"])); ts.append(float(row["capture_ts"]))
    return np.array(idx), np.array(ts)


def judge(run_json):
    j = json.loads(run_json.read_text())
    jd = j.get("judgments") or {}
    pick_h = (jd.get("pick") or {}).get("human_verdict")
    place_h = (jd.get("place") or {}).get("human_verdict")
    return pick_h, place_h, j


def build_one(run_dir, out_dir, args):
    stem = run_dir.name
    rec = run_dir / "recording"
    run_json = run_dir / f"{stem}.json"
    need = [run_json, rec / "states.csv", rec / "top.mp4", rec / "top_frame_log.csv"]
    missing = [p.name for p in need if not p.exists()]
    if missing:
        return {"run": stem, "used": False, "reason": "missing:" + ",".join(missing)}

    pick_h, place_h, _ = judge(run_json)
    if not args.include_failed and not (pick_h == "yes" and place_h == "yes"):
        return {"run": stem, "used": False, "reason": f"human_verdict pick={pick_h} place={place_h}"}

    at, aq, gt, gs = load_states(rec / "states.csv")
    if len(at) < MIN_ACTUAL_SAMPLES:
        return {"run": stem, "used": False, "reason": f"actual 実測が少ない ({len(at)})"}
    order = np.argsort(at); at, aq = at[order], aq[order]
    at, aq = drop_spikes(at, aq)
    fidx, fts = load_frame_log(rec / "top_frame_log.csv")
    if len(fts) < FPS:
        return {"run": stem, "used": False, "reason": f"top フレームが少ない ({len(fts)})"}

    t0, t1 = max(fts[0], at[0]), min(fts[-1], at[-1])
    if t1 - t0 < 3.0:
        return {"run": stem, "used": False, "reason": "記録の重なりが短い"}
    t = np.arange(t0, t1, 1.0 / FPS)

    q = np.stack([np.interp(t, at, aq[:, k]) for k in range(6)], axis=1)
    g = np.zeros(len(t))
    if len(gt):
        go = np.argsort(gt); gt, gs = gt[go], gs[go]
        for i, ti in enumerate(t):
            k = np.searchsorted(gt, ti, side="right") - 1
            g[i] = gs[k] if k >= 0 else 0.0
    state = np.concatenate([q, g[:, None]], axis=1).astype(np.float32)
    actions = np.concatenate([state[1:], state[-1:]], axis=0)

    # 停止区間を詰める
    motion = np.max(np.abs(actions - state), axis=1)
    keep = np.ones(len(t), dtype=bool)
    i, idle_trim_steps = 0, 0
    while i < len(t):
        if motion[i] < IDLE_EPS_DEG:
            j = i
            while j < len(t) and motion[j] < IDLE_EPS_DEG:
                j += 1
            if (j - i) / FPS > IDLE_MAX_SEC:
                cut_from = i + int(IDLE_KEEP_SEC * FPS)
                keep[cut_from:j] = False
                idle_trim_steps += j - cut_from
            i = j
        else:
            i += 1
    t, state, actions = t[keep], state[keep], actions[keep]

    # 各ステップに最も近い上カメラのフレーム
    nearest = np.clip(np.searchsorted(fts, t), 1, len(fts) - 1)
    left = fts[nearest - 1]; right = fts[nearest]
    nearest = np.where(np.abs(t - left) <= np.abs(right - t), nearest - 1, nearest)
    want = {int(fidx[n]): [] for n in nearest}
    for step, n in enumerate(nearest):
        want[int(fidx[n])].append(step)

    if out_dir.exists():
        if not args.force:
            return {"run": stem, "used": True, "reason": "既存 (スキップ・--force で再生成)",
                    "steps": int(len(t))}
        shutil.rmtree(out_dir)
    (out_dir / "frames").mkdir(parents=True)

    cap = cv2.VideoCapture(str(rec / "top.mp4"))
    fi, written, max_need = 0, 0, max(want)
    size = None
    while fi <= max_need:
        ok, frame = cap.read()
        if not ok:
            break
        if fi in want:
            h, w = frame.shape[:2]
            s = IMG_LONG / max(h, w)
            small = cv2.resize(frame, (round(w * s), round(h * s)), interpolation=cv2.INTER_AREA)
            size = small.shape[1], small.shape[0]
            for step in want[fi]:
                cv2.imwrite(str(out_dir / "frames" / f"{step:06d}.jpg"), small,
                            [cv2.IMWRITE_JPEG_QUALITY, JPEG_QUALITY])
                written += 1
        fi += 1
    cap.release()
    if written != len(t):
        shutil.rmtree(out_dir)
        return {"run": stem, "used": False,
                "reason": f"フレーム抽出不足 written={written} steps={len(t)} (mp4 と frame_log の不一致)"}

    np.savez_compressed(out_dir / "episode.npz", t=t - t[0], state=state, actions=actions)
    meta = {
        "run_stem": stem, "task": TASK, "fps": FPS, "steps": int(len(t)),
        "duration_sec": round(len(t) / FPS, 1),
        "idle_trimmed_sec": round(idle_trim_steps / FPS, 1),
        "image_size": size, "state_dim": 7,
        "state_names": ["j0", "j1", "j2", "j3", "j4", "j5", "gripper"],
        "action": "absolute target = state 0.1s later",
        "actual_samples": int(len(at)), "gripper_cmds": int(len(gt)),
        "human_verdict": {"pick": pick_h, "place": place_h},
    }
    (out_dir / "meta.json").write_text(json.dumps(meta, indent=2, ensure_ascii=False))
    return {"run": stem, "used": True, "reason": "ok", "steps": int(len(t)),
            "idle_trimmed_sec": meta["idle_trimmed_sec"]}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--dataset", default=DEFAULT_DATASET)
    ap.add_argument("--since", default="20261015", help="run_stem の日付 (YYYYMMDD) 以降")
    ap.add_argument("--run", action="append", help="特定の run_stem だけ (複数可)")
    ap.add_argument("--include-failed", action="store_true", help="人の判定 no も含める (分析用)")
    ap.add_argument("--force", action="store_true", help="既存エピソードを作り直す")
    args = ap.parse_args()
    ensure_ssd()

    ds = DATA_ROOT / "datasets" / args.dataset
    out_root = ds / "raw_episodes"
    out_root.mkdir(parents=True, exist_ok=True)
    runs = sorted(p for p in RUNS_ROOT.glob("run_*") if p.is_dir())
    if args.run:
        runs = [p for p in runs if p.name in set(args.run)]
    else:
        runs = [p for p in runs if p.name.split("_")[2] >= args.since]
        runs = [p for p in runs if (p / "recording" / "top.mp4").exists()]

    results = []
    for r in runs:
        try:
            res = build_one(r, out_root / r.name, args)
        except Exception as e:
            res = {"run": r.name, "used": False, "reason": f"exception:{type(e).__name__}:{e}"}
        results.append(res)
        flag = "OK " if res["used"] else "-- "
        print(f"[{flag}] {res['run']}  {res.get('steps', '')}  {res['reason']}")

    index_path = ds / "index.json"
    old = json.loads(index_path.read_text()) if index_path.exists() else {}
    for res in results:
        old[res["run"]] = res
    index_path.write_text(json.dumps(old, indent=2, ensure_ascii=False))
    used = [v for v in old.values() if v.get("used")]
    print(f"\n採用エピソード合計: {len(used)}  総ステップ: {sum(v.get('steps', 0) for v in used)}"
          f"  → {out_root}")


if __name__ == "__main__":
    main()
