#!/usr/bin/env python3
"""export_so101_raw_episodes.py — SO-101 のお手本 (LeRobot v3.0) を, openpi で変換できる raw_episodes と tar にする (依頼 280).

openpi の LeRobot は v3.0 を読めないので, mechArm と同じく Mac でエピソードごとに書き出し, Pod で変換する
(pod_prep_so101.sh → convert_so101_to_lerobot.py).

Mac の lerobot の環境 (conda の lerobot. av1 を読める pyav) で流す:
  /opt/homebrew/Caskroom/miniforge/base/envs/lerobot/bin/python pi05/export_so101_raw_episodes.py
  (--dry-run: 選ぶ本と本数だけ出して何も書かない)

元 (読むだけ. 書き換えない): ~/so101_datasets/ の 3 つ
  so101_redblock_box_teleop_v1        場所 1 (episode_labels.json に place がない. 全部 1)
  so101_redblock_box_teleop_v1_pos23  場所 2・3
  so101_redblock_box_teleop_v1_pos45  場所 4・5
採るのは各フォルダの episode_labels.json で label が success の本だけ. 場所ごとの本数が
EXPECT_PER_PLACE (8・10・10・10・10) と違えば, 何も書かずに止まる.

出力: /Volumes/KIOXIA/r2r2r-data/datasets/so101_redblock_box_teleop_even_v1/
  raw_episodes/<元の名前>_ep<番号>/episode.npz   state・actions (どちらも関節 6 つ. 元の値のまま float32.
                                                 actions は元の action = リーダーの目標で絶対値. 差分にするのは学習の設定)
                                    frames_desk/000000.jpg …   机側のカメラ (320x240 に縮める)
                                    frames_wrist/000000.jpg …  手首のカメラ (同じ)
                                    meta.json
  index.json                        選んだ本・場所ごとの本数・コマ数・確かめの結果
  so101_redblock_box_teleop_even_v1_raw_episodes.tar   (raw_episodes/ を入れる. ._ は入れない)
同じ名前のフォルダがあれば止まる (上書きしない). 一時フォルダに書いて確かめてから名前を変える.

書いたあとに確かめること: 本数・各本のコマ数が元と同じ / npz の state・actions が元の parquet と1つ残らず同じ /
各本の jpg がカメラごとにコマ数と同じ枚数. tar に入れたあと tar の中の本数も数える.
"""
import argparse
import hashlib
import json
import os
import subprocess
import sys
from collections import Counter
from pathlib import Path

import av
import numpy as np
import pandas as pd
from PIL import Image

SRC_ROOT = Path.home() / "so101_datasets"
SOURCES = (                             # (フォルダ, place が書いていないときの場所)
    ("so101_redblock_box_teleop_v1", 1),
    ("so101_redblock_box_teleop_v1_pos23", None),
    ("so101_redblock_box_teleop_v1_pos45", None),
)
NAME = "so101_redblock_box_teleop_even_v1"
OUT_ROOT = Path("/Volumes/KIOXIA/r2r2r-data/datasets")
EXPECT_PER_PLACE = {1: 8, 2: 10, 3: 10, 4: 10, 5: 10}
TASK = "Put the red block into the white box"
CAMERAS = ("desk", "wrist")
JOINTS = ["shoulder_pan.pos", "shoulder_lift.pos", "elbow_flex.pos", "wrist_flex.pos", "wrist_roll.pos", "gripper.pos"]
FPS = 30
OUT_W, OUT_H = 320, 240
JPEG_Q = 95


def sha256(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for b in iter(lambda: f.read(1 << 20), b""):
            h.update(b)
    return h.hexdigest()


def pick(src_root):
    """各フォルダの success の本を選ぶ → [(フォルダ, episode_index, place)]"""
    chosen = []
    for d, default_place in SOURCES:
        lab = json.loads((src_root / d / "episode_labels.json").read_text())
        if lab.get("dataset") != f"local/{d}":
            sys.exit(f"[ERROR] {d}/episode_labels.json の dataset が違う: {lab.get('dataset')}")
        for e in lab["episodes"]:
            if e["label"] not in ("success", "fail"):
                sys.exit(f"[ERROR] {d} episode {e['episode_index']} の label が success でも fail でもない: {e['label']}")
            if e["label"] != "success":
                continue
            place = e.get("place", default_place)
            if place is None:
                sys.exit(f"[ERROR] {d} episode {e['episode_index']} に place がない")
            chosen.append((d, int(e["episode_index"]), int(place)))
    return chosen


def load_source(src_root, d):
    root = src_root / d
    info = json.loads((root / "meta" / "info.json").read_text())
    assert info["codebase_version"] == "v3.0", f"{d}: v3.0 ではない"
    assert int(info["fps"]) == FPS, f"{d}: fps {info['fps']}"
    for k in ("observation.state", "action"):
        assert info["features"][k]["names"] == JOINTS, f"{d}: {k} の関節の名前が違う"
    for c in CAMERAS:
        f = info["features"][f"observation.images.{c}"]
        assert f["shape"] == [480, 640, 3] and f["info"]["video.codec"] == "av1", f"{d}: {c} のカメラが 640x480 av1 ではない"
    data = pd.concat([pd.read_parquet(p) for p in sorted((root / "data").glob("chunk-*/file-*.parquet"))], ignore_index=True)
    eps = pd.concat([pd.read_parquet(p) for p in sorted((root / "meta" / "episodes").glob("chunk-*/file-*.parquet"))],
                    ignore_index=True).set_index("episode_index")
    tasks = pd.read_parquet(root / "meta" / "tasks.parquet")
    task_of = {int(r.task_index): t for t, r in tasks.iterrows()}
    return info, data, eps, task_of


def episode_arrays(data, ep, length, task_of):
    rows = data[data["episode_index"] == ep].sort_values("frame_index")
    assert len(rows) == length, f"episode {ep}: parquet の行 {len(rows)} と length {length} が違う"
    assert np.array_equal(rows["frame_index"].to_numpy(), np.arange(length)), f"episode {ep}: frame_index が 0 から続いていない"
    tasks = {task_of[int(t)] for t in rows["task_index"]}
    assert tasks == {TASK}, f"episode {ep}: 課題の言葉が違う {tasks}"
    state = np.stack(rows["observation.state"].to_numpy()).astype(np.float32)
    actions = np.stack(rows["action"].to_numpy()).astype(np.float32)
    assert state.shape == actions.shape == (length, 6)
    return state, actions


def video_path(src_root, d, info, eps, ep, cam):
    key = f"observation.images.{cam}"
    return src_root / d / info["video_path"].format(video_key=key, chunk_index=int(eps.loc[ep, f"videos/{key}/chunk_index"]),
                                                    file_index=int(eps.loc[ep, f"videos/{key}/file_index"]))


def write_frames(src_root, d, info, eps, picked, out_dirs, cam):
    """1 つの動画ファイルを頭から順に読み, 選んだ本のコマを jpg にする. コマの番号は時刻 × fps で決める"""
    key = f"observation.images.{cam}"
    by_file = {}
    for ep in picked:
        start = round(float(eps.loc[ep, f"videos/{key}/from_timestamp"]) * FPS)
        end = round(float(eps.loc[ep, f"videos/{key}/to_timestamp"]) * FPS)
        length = int(eps.loc[ep, "length"])
        assert end - start == length, f"{d} episode {ep} {cam}: 動画の長さ {end - start} コマと length {length} が違う"
        by_file.setdefault(video_path(src_root, d, info, eps, ep, cam), []).append((start, length, ep))
    written = Counter()
    for path, spans in by_file.items():
        want = {}
        for start, length, ep in spans:
            for i in range(length):
                want[start + i] = (ep, i)
        with av.open(str(path)) as c:
            for fr in c.decode(video=0):
                g = round(float(fr.time) * FPS)
                if g not in want:
                    continue
                ep, i = want.pop(g)
                img = fr.to_image()
                assert img.size == (640, 480), f"{path}: コマの大きさ {img.size}"
                img.resize((OUT_W, OUT_H), Image.Resampling.BOX).save(out_dirs[ep] / f"frames_{cam}" / f"{i:06d}.jpg",
                                                                       quality=JPEG_Q)
                written[ep] += 1
        assert not want, f"{path}: 動画に見つからないコマ {len(want)} 枚 (最初 {min(want)})"
    return written


def verify(out, chosen, src_root):
    """書いたものを読み直して元と比べる → (本数, 合計コマ数)"""
    total = 0
    cache = {}
    for d, ep, place in chosen:
        if d not in cache:
            cache[d] = load_source(src_root, d)
        _, data, eps, task_of = cache[d]
        length = int(eps.loc[ep, "length"])
        st, ac = episode_arrays(data, ep, length, task_of)
        e = out / "raw_episodes" / f"{d}_ep{ep:03d}"
        z = np.load(e / "episode.npz")
        assert np.array_equal(z["state"], st) and np.array_equal(z["actions"], ac), f"{e.name}: state・actions が元と違う"
        meta = json.loads((e / "meta.json").read_text())
        assert meta["steps"] == length and meta["place"] == place
        for cam in CAMERAS:
            jpgs = sorted(p.name for p in (e / f"frames_{cam}").glob("[!.]*.jpg"))
            assert jpgs == [f"{i:06d}.jpg" for i in range(length)], f"{e.name}: {cam} の jpg が {len(jpgs)} 枚 (コマは {length})"
            with Image.open(e / f"frames_{cam}" / jpgs[-1]) as im:
                assert im.size == (OUT_W, OUT_H)
        total += length
    n = len(list((out / "raw_episodes").glob("[!.]*/episode.npz")))
    assert n == len(chosen), f"raw_episodes の本数 {n} (選んだのは {len(chosen)})"
    return n, total


def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument("--src-root", default=str(SRC_ROOT))
    ap.add_argument("--out-root", default=str(OUT_ROOT))
    ap.add_argument("--dry-run", action="store_true", help="選ぶ本と本数だけ出して何も書かない")
    args = ap.parse_args(argv)
    src_root, out_root = Path(args.src_root).expanduser(), Path(args.out_root)

    chosen = pick(src_root)
    per_place = Counter(p for _, _, p in chosen)
    print(f"[PICK  ] success の本 {len(chosen)} 本  場所ごと {dict(sorted(per_place.items()))}")
    if dict(per_place) != EXPECT_PER_PLACE:
        sys.exit(f"[ERROR] 場所ごとの本数が {EXPECT_PER_PLACE} と違う: {dict(sorted(per_place.items()))}. 何も書かずに止めます")
    if args.dry_run:
        for d, ep, p in chosen:
            print(f"   場所 {p}  {d} episode {ep}")
        return 0

    if not out_root.is_dir():
        sys.exit(f"[ERROR] SSD 未マウント (または置き場所がない): {out_root}")
    out = out_root / NAME
    if out.exists():
        sys.exit(f"[ERROR] もうある (上書きしない): {out}")
    tmp = out_root / f".{NAME}.tmp.{os.getpid()}"
    (tmp / "raw_episodes").mkdir(parents=True)

    index = {"name": NAME, "request": "依頼 280", "task": TASK, "fps": FPS, "image_size": [OUT_W, OUT_H],
             "source_image_size": [640, 480], "cameras": {c: f"frames_{c}" for c in CAMERAS}, "joints": JOINTS,
             "actions": "元の action (リーダーの目標. 関節 6 つの絶対値). 学習で関節 5 つを差分・爪は絶対値にする",
             "pick_rule": "各フォルダの episode_labels.json の label == success", "sources": {}, "episodes": []}
    for d, default_place in SOURCES:
        picked = [ep for dd, ep, _ in chosen if dd == d]
        info, data, eps, task_of = load_source(src_root, d)
        index["sources"][d] = {"path": str(src_root / d), "total_episodes": int(info["total_episodes"]),
                               "picked": picked,
                               "labels_sha256": sha256(src_root / d / "episode_labels.json"),
                               "data_sha256": {str(p.relative_to(src_root / d)): sha256(p)
                                               for p in sorted((src_root / d / "data").glob("chunk-*/file-*.parquet"))}}
        out_dirs = {}
        for ep in picked:
            length = int(eps.loc[ep, "length"])
            state, actions = episode_arrays(data, ep, length, task_of)
            e = tmp / "raw_episodes" / f"{d}_ep{ep:03d}"
            for cam in CAMERAS:
                (e / f"frames_{cam}").mkdir(parents=True)
            np.savez(e / "episode.npz", state=state, actions=actions)
            place = next(p for dd, x, p in chosen if dd == d and x == ep)
            meta = {"task": TASK, "fps": FPS, "steps": length, "image_size": [OUT_W, OUT_H], "state_dim": 6,
                    "state_names": JOINTS, "action": "leader target (absolute, same as source action)",
                    "cameras": {c: f"frames_{c}" for c in CAMERAS},
                    "source_dataset": f"local/{d}", "source_episode_index": ep, "place": place, "label": "success"}
            (e / "meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=2) + "\n")
            out_dirs[ep] = e
            index["episodes"].append({"dir": e.name, "place": place, "source": d, "episode_index": ep, "steps": length})
        for cam in CAMERAS:
            written = write_frames(src_root, d, info, eps, picked, out_dirs, cam)
            for ep in picked:
                assert written[ep] == int(eps.loc[ep, "length"]), f"{d} episode {ep} {cam}: jpg {written[ep]} 枚"
        print(f"[WRITE ] {d}: {len(picked)} 本 (episode {picked})")

    n, total = verify(tmp, chosen, src_root)
    by_place = {}
    for x in index["episodes"]:
        b = by_place.setdefault(str(x["place"]), {"episodes": 0, "frames": 0})
        b["episodes"] += 1
        b["frames"] += x["steps"]
    index["summary"] = {"episodes": n, "frames": total, "by_place": by_place}
    index["verify"] = ("本数・各本のコマ数が元と同じ / npz の state・actions が元の parquet と完全に同じ / "
                       "各本の jpg がカメラごとにコマ数と同じ枚数: OK")
    print(f"[VERIFY] {n} 本・{total} コマ: 元と同じ (本数・コマ数・関節の値・jpg の枚数)")

    tar = tmp / f"{NAME}_raw_episodes.tar"
    env = dict(os.environ, COPYFILE_DISABLE="1")          # macOS の ._ を tar に入れない
    subprocess.run(["tar", "cf", str(tar), "--exclude", "._*", "-C", str(tmp), "raw_episodes"], check=True, env=env)
    names = subprocess.run(["tar", "tf", str(tar)], check=True, capture_output=True, text=True).stdout.splitlines()
    n_tar = sum(1 for x in names if x.endswith("/episode.npz") and not x.split("/")[-1].startswith("._"))
    n_jpg = sum(1 for x in names if x.endswith(".jpg") and "/._" not in x)
    assert n_tar == n and n_jpg == 2 * total, f"tar の中: 本数 {n_tar}・jpg {n_jpg} (書いたのは {n} 本・{2 * total} 枚)"
    assert not any("/._" in x for x in names), "tar に ._ が入っている"
    index["tar"] = {"path": tar.name, "bytes": tar.stat().st_size, "sha256": sha256(tar), "episodes": n_tar, "jpg": n_jpg}
    (tmp / "index.json").write_text(json.dumps(index, ensure_ascii=False, indent=2) + "\n")
    tmp.rename(out)
    print(f"[TAR   ] {out / tar.name}  {index['tar']['bytes']} バイト  sha256 {index['tar']['sha256'][:12]}…  (中 {n_tar} 本・jpg {n_jpg} 枚)")
    print(f"[DONE  ] {out}  場所ごと {json.dumps(by_place, ensure_ascii=False)}")
    return 0


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