"""依頼 347: 依頼 346 の道で録った 50 本 (19:03〜19:50) から, 確かめに使う数字を 1 つの JSON にまとめる (読むだけ. アーム・カメラは使わない).

1 本ごと: 答え (成功・失敗の番号)・置いた所 (画素・向き・机の上の位置)・道のつかむ所 (送った関節角)・その時の実際の関節角・
  閉じる直前 (GRASP_OPEN のコマ +8) の手首カメラのブロックの写り (赤い塊の画素数・重心・傾き・縁で切れているか).
  傾き = 赤い塊を囲む最小の長方形の向き (画像の横を 0°. -45〜+45. 立方体なので 90° で同じ).
  手首カメラは爪 (gripper) に固定なので, 画像の横 = 爪に対する決まった向き. 爪に対するブロックの傾きは 成功した本の中央値を 0 として見る.
  絵: 閉じる直前の手首カメラを 50 本並べた絵 (wrist_grasp_347.png. 依頼 346 の後で Claude が作った ep_grasp_wrist_tmp.png と同じ中身).

  python so101/check_347/extract_347.py    → so101/check_347/episodes_347.json, wrist_grasp_347.png
"""
import glob
import json
import sys
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
sys.path.insert(0, str(SO101 / "sim"))
sys.path.insert(0, str(SO101 / "ideal_var"))
import sim_330 as S  # noqa: E402

REC = Path("/Volumes/KIOXIA/r2r2r-data/lab/so101_Log12/315/record")
DS = "so101_redblock_box_ideal_var_v1"
AFTER_OPEN = 8          # GRASP_OPEN のコマから何コマあと (依頼文と同じ)
HSV = ((10, 165), 70, 50)


def red_blob(img):
    """いちばん大きい赤い塊 → 画素数・重心・傾き (最小の長方形. -45〜+45)・縁までの画素. なければ None"""
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    (hl, hh), smin, vmin = HSV
    m = (((hsv[..., 0] < hl) | (hsv[..., 0] > hh)) & (hsv[..., 1] > smin) & (hsv[..., 2] > vmin)).astype(np.uint8)
    m = cv2.morphologyEx(m, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
    n, lab, st, cen = cv2.connectedComponentsWithStats(m, connectivity=8)
    if n <= 1:
        return None
    k = 1 + int(np.argmax(st[1:, cv2.CC_STAT_AREA]))
    ys, xs = np.nonzero(lab == k)
    (cx, cy), (w, h), ang = cv2.minAreaRect(np.c_[xs, ys].astype(np.float32))
    tilt = (ang + 45.0) % 90.0 - 45.0
    hull = cv2.convexHull(np.c_[xs, ys].astype(np.int32))
    # 爪で隠れた所があると長方形の向きが崩れるので, 輪郭の長い辺の向きも出す (重さ = 辺の長さ)
    poly = cv2.approxPolyDP(hull, 3.0, True).reshape(-1, 2).astype(np.float64)
    ed = np.roll(poly, -1, 0) - poly
    L = np.linalg.norm(ed, axis=1)
    ea = (np.degrees(np.arctan2(ed[:, 1], ed[:, 0])) + 45.0) % 90.0 - 45.0
    # 辺の向きの重みつきの平均 (90° ごとに同じ: 4 倍の角で平均)
    z = np.sum(L * np.exp(1j * np.radians(4 * ea)))
    tilt_edges = float(np.degrees(np.angle(z)) / 4.0)
    return {"area": int(len(xs)), "u": round(float(xs.mean()), 1), "v": round(float(ys.mean()), 1),
            "rect_wh": [round(float(w), 1), round(float(h), 1)], "tilt_rect_deg": round(float(tilt), 1),
            "tilt_edges_deg": round(tilt_edges, 1),
            "edge_px": int(min(xs.min(), ys.min(), img.shape[1] - 1 - xs.max(), img.shape[0] - 1 - ys.max()))}


def wrist_frame(ep, f):
    """1 本 1 ファイルの記録 (meta/episodes/chunk-000/file-{ep}.parquet) から手首カメラの f コマ目 (BGR)"""
    import av
    import pandas as pd
    root = S.DATASETS / DS
    e = pd.read_parquet(root / f"meta/episodes/chunk-000/file-{ep:03d}.parquet").set_index("episode_index").loc[ep]
    k = "videos/observation.images.wrist"
    fn = root / f"{k}/chunk-{int(e[k + '/chunk_index']):03d}/file-{int(e[k + '/file_index']):03d}.mp4"
    t0 = float(e[k + "/from_timestamp"])
    with av.open(str(fn)) as c:
        s = c.streams.video[0]
        for fr in c.decode(s):
            if int(round((float(fr.pts * s.time_base) - t0) * S.FPS)) == f:
                return fr.to_ndarray(format="bgr24")
    raise SystemExit(f"{fn}: {f} コマ目がない")


def main():
    labels = json.loads((S.DATASETS / DS / "episode_labels.json").read_text())["episodes"]
    out, tiles = [], []
    for e in labels:
        i = e["plan_index"]
        pj = sorted(glob.glob(str(REC / f"i{i:02d}_*_path.json")))
        rj = sorted(glob.glob(str(REC / f"i{i:02d}_*_run.json")))
        if len(pj) != 1 or len(rj) != 1:
            raise SystemExit(f"{i}: 道・記録が 1 つでない {pj} {rj}")
        p, r = json.loads(Path(pj[0]).read_text()), json.loads(Path(rj[0]).read_text())
        kf = {k["name"]: k["frame"] for k in p["keyframes"]}
        f = kf["GRASP_OPEN"] + AFTER_OPEN
        st = np.asarray(r["state"], np.float64)
        sent = np.asarray(r["sent"], np.float64)
        img = wrist_frame(e["episode_index"], f)
        blob = red_blob(img)
        out.append({"index": i, "episode_index": e["episode_index"], "label": e["label"], "fail_reason": e["fail_reason"],
                    "pixel": e["block_pixel"], "yaw": e["yaw"], "block_xy_mm": e["block_xy_mm"], "detour": e["detour"],
                    "start_offset": e["start_offset"], "roll_add": e["roll_add_grasp"],
                    "grasp": e["grasp"], "frame": f, "grasp_open_frame": kf["GRASP_OPEN"],
                    "sent_at": sent[f].round(3).tolist(), "state_at": st[f].round(3).tolist(),
                    "state_grasp_open": st[kf["GRASP_OPEN"]].round(3).tolist(),
                    "state_grasp_closed": st[kf["GRASP_CLOSED"]].round(3).tolist(),
                    "wrist": blob, "desk_jpg": Path(pj[0]).name.replace("_path.json", "_desk.jpg")})
        t = cv2.resize(img, (320, 240))
        col = (60, 200, 60) if e["label"] == "success" else (40, 40, 230)
        cv2.rectangle(t, (0, 0), (319, 239), col, 6)
        txt = f"{i + 1} {'OK' if e['label'] == 'success' else 'NG' + e['fail_reason']} a{blob['area'] if blob else 0}"
        cv2.putText(t, txt, (8, 26), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 3)
        cv2.putText(t, txt, (8, 26), cv2.FONT_HERSHEY_SIMPLEX, 0.7, col, 2)
        tiles.append(t)
        print(i + 1, e["label"], e["fail_reason"], blob)
    rows = [np.hstack(tiles[k:k + 10] + [np.zeros_like(tiles[0])] * (10 - len(tiles[k:k + 10]))) for k in range(0, len(tiles), 10)]
    cv2.imwrite(str(HERE / "wrist_grasp_347.png"), cv2.resize(np.vstack(rows), None, fx=0.6, fy=0.6))
    (HERE / "episodes_347.json").write_text(json.dumps({"request": 347, "source": str(REC), "dataset": DS,
                                                       "after_open_frames": AFTER_OPEN, "episodes": out},
                                                      ensure_ascii=False, indent=1) + "\n")


if __name__ == "__main__":
    main()
