#!/usr/bin/env python3
"""依頼 405: 握れたかの判定 (爪の読み) の境目を 記録から決め, 記録に当てて取り違えを数える (読むだけ・アームなし).

使う記録 (KIOXIA は読むだけ):
  - so101f の実機 30 回・so101g の実機 7 回 (台帳 so101_trials.csv の結果 y/n のある回. 記録の observation.state・action)
  - お手本 64 本 (datasets/so101_redblock_box_ideal_var_v2_success_recover_v1. success 50 本・recover 14 本. episode.npz の state・actions)
  - 参考: code_rule401 の実機 56 回 (依頼 401. 成功の回だけ)
閉じた所: 爪の指令 (action) が 開き (CMD_OPEN 25 以上) のあと CMD_CLOSE (20) を割った最初のコマ k. そのうち つかむ高さ
  (手先 (URDF) の z が GRASP_Z_MAX 70 mm 未満) のものだけ (箱で離したあと HOME で閉じるのは数えない)
本当の答え (truth): k + 8 コマから k + 60 コマの間で 爪の指令が 5 未満のまま 10 コマ以上続く いちばん長い区間の 最後の 5 コマの爪の読みの中央値.
  9 以上 = 挟んだ・5 未満 = 空・その間 = 中途 (switch_405 の HELD_MIN・EMPTY_MAX). その区間がない (モデルが すぐ開き直した) 閉じは数えない
  (切り替え方式では コードが閉じたまま待つので, 開き直す動きは起きない)
判定 (judge. switch_405 と同じ関数 judge_reading): 判定を始めるコマから START (3) コマ目以降で 続けて N (4) コマの爪の読みの幅が W (0.5) 以下に
  なったら 落ち着いたとし, そのコマの読みで 挟んだ (HELD_MIN 9 〜 HELD_MAX 12)・空 (EMPTY_MAX 5 未満)・あいまい (その間・12 より上・
  MAX_WAIT 30 コマで落ち着かない) に分ける. あいまいは空として扱う
  判定を始めるコマは 2 通りで数える: (a) 指令が 20 を割ったコマ (切り替え方式でコードが受け取るコマ) / (b) 指令が 5 を割ったコマ (記録では
  モデル・お手本の指令がゆっくり閉じるので, コードが 1 コマで閉じる形に近い所)
持ち上げの途中の確かめ: 挟んだ回の k + 20 〜 k + 60 コマの爪の読みの最小 (成功の回) と so101g の「持ち上げで落とす」回

  P=/opt/homebrew/Caskroom/miniforge/base/envs/lerobot/bin/python
  $P so101/check_405/analyze_405.py          → so101/check_405/judge_405.json・judge_405.md
"""
import csv
import json
import sys
from collections import Counter
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
for p in (SO101, SO101 / "ideal_var", HERE):
    if str(p) not in sys.path:
        sys.path.insert(0, str(p))

import switch_405 as SW  # noqa: E402

LOG = Path("/Volumes/KIOXIA/r2r2r-data/lab/so101_Log12")
DEMO = Path("/Volumes/KIOXIA/r2r2r-data/datasets/so101_redblock_box_ideal_var_v2_success_recover_v1/raw_episodes")
GRASP_Z_MAX = 70.0
OUT_JSON, OUT_MD = HERE / "judge_405.json", HERE / "judge_405.md"
KINDS = ("so101f", "so101g", "demo_success", "demo_recover", "code_rule401")
KIND_JA = {"so101f": "so101f 実機 30 回", "so101g": "so101g 実機 7 回", "demo_success": "お手本 success 50 本",
           "demo_recover": "お手本 recover 14 本", "code_rule401": "参考: code_rule401 実機 56 回"}


def load():
    import pandas as pd
    import run_so101_policy as R
    out = []
    with open(LOG / R.TRIALS_CSV, newline="") as f:
        rows = [dict(zip(R.TRIAL_COLUMNS, r)) for r in list(csv.reader(f))[1:]]
    for r in rows:
        kind = r["model"].split()[0]
        if kind not in ("so101f", "so101g", "code_rule401") or r["execute"] != "1" or r["result"] not in ("success", "failure"):
            continue
        if kind == "code_rule401" and r["result"] != "success":
            continue
        f = sorted(p for p in (Path(r["record_dir"]) / "data").glob("*/*.parquet") if not p.name.startswith("._"))
        if not f:
            continue
        df = pd.read_parquet(f[0])
        out.append({"kind": kind, "name": r["trial"], "result": r["result"], "fail_reason": r["fail_reason"], "place": r["place"],
                    "S": np.stack(df["observation.state"].values).astype(np.float64),
                    "A": np.stack(df["action"].values).astype(np.float64)})
    for p in sorted(x for x in DEMO.iterdir() if not x.name.startswith(".")):
        z = np.load(p / "episode.npz")
        out.append({"kind": "demo_recover" if "recover" in p.name else "demo_success", "name": p.name, "result": "success",
                    "fail_reason": "", "place": "", "S": z["state"].astype(np.float64), "A": z["actions"].astype(np.float64)})
    return out


def close_events(A):
    g, armed, ev = A[:, 5], False, []
    for k in range(len(g)):
        if g[k] >= SW.CMD_OPEN:
            armed = True
        elif armed and g[k] < SW.CMD_CLOSE:
            ev.append(k)
            armed = False
    return ev


def truth(s, a, k):
    n, best, j = len(s), None, k + 8
    end = min(k + 60, n)
    while j < end:
        if a[j] < 5.0:
            e = j
            while e + 1 < end and a[e + 1] < 5.0:
                e += 1
            if e - j + 1 >= 10 and (best is None or e - j > best[1] - best[0]):
                best = (j, e)
            j = e + 1
        else:
            j += 1
    if best is None:
        return None, None
    v = float(np.median(s[best[1] - 4:best[1] + 1]))
    return ("held" if v >= SW.HELD_MIN else "empty" if v < SW.EMPTY_MAX else "partial"), round(v, 2)


def judge_from(s, k0):
    """記録の爪の読み s を k0 から 1 コマずつ judge_reading に渡す (switch_405 と同じ)"""
    reads = []
    for j in range(k0, min(k0 + SW.JUDGE["max_wait"] + 1, len(s))):
        reads.append(float(s[j]))
        r = SW.judge_reading(reads)
        if r is not None:
            return r
    return {"class": "ambiguous", "why": "記録が終わった", "frames": len(reads), "grip": float(s[min(k0 + len(reads) - 1, len(s) - 1)]),
            "settled": False}


def main():
    import var_lib_314 as V
    ch = V.load_urdf_chain(V.URDF)
    recs = load()
    ev_rows = []
    for r in recs:
        S, A = r["S"], r["A"]
        for k in close_events(A):
            z = float(V.tcp_mm(ch, S[k, :5])[2])
            if z >= GRASP_Z_MAX:
                continue
            t, tv = truth(S[:, 5], A[:, 5], k)
            k5 = next((j for j in range(k, min(k + 15, len(A))) if A[j, 5] < 5.0), k)
            ja, jb = judge_from(S[:, 5], k), judge_from(S[:, 5], k5)
            g20 = float(S[min(k + 20, len(S) - 1), 5])
            fixed20 = "held" if SW.HELD_MIN <= g20 <= SW.HELD_MAX else "empty" if g20 < SW.EMPTY_MAX else "ambiguous"
            ev_rows.append({"kind": r["kind"], "name": r["name"], "result": r["result"], "fail_reason": r["fail_reason"], "frame": k,
                            "tcp_z_mm": round(z, 1), "truth": t, "truth_grip": tv,
                            "judge_a": ja["class"], "judge_a_frames": ja["frames"], "judge_a_grip": round(ja["grip"], 2),
                            "judge_b": jb["class"], "judge_b_frames": jb["frames"], "judge_b_grip": round(jb["grip"], 2),
                            "fixed20": fixed20, "grip_k20": round(g20, 2)})
    # 持ち上げの途中: 成功の回の 挟んだ閉じ (truth held) の k+20〜k+60 の最小
    lift = {}
    for kind in KINDS:
        mins = []
        for e in ev_rows:
            if e["kind"] != kind or e["result"] != "success" or e["truth"] != "held":
                continue
            S = next(r["S"] for r in recs if r["name"] == e["name"] and r["kind"] == kind)
            mins.append(float(S[e["frame"] + 20:e["frame"] + 60, 5].min()))
        if mins:
            lift[kind] = {"n": len(mins), "min": round(min(mins), 2), "median": round(float(np.median(mins)), 2), "max": round(max(mins), 2)}
    drops = []
    for r in recs:
        if r["fail_reason"] == "3":
            S, A = r["S"], r["A"]
            for k in close_events(A):
                z0 = float(V.tcp_mm(ch, S[k, :5])[2])
                if z0 >= GRASP_Z_MAX:
                    continue
                seg = S[k:k + 90]
                zz = [float(V.tcp_mm(ch, q[:5])[2]) for q in seg]
                drops.append({"name": r["name"], "kind": r["kind"], "frame": k, "grip_every5": np.round(seg[::5, 5], 1).tolist(),
                              "cmd_every5": np.round(A[k:k + 90:5, 5], 1).tolist(), "tcp_z_every5": np.round(zz[::5], 1).tolist()})
    tables = {}
    for col in ("judge_a", "judge_b", "fixed20"):
        c = Counter((e["kind"], e["truth"], e[col]) for e in ev_rows if e["truth"] is not None)
        tables[col] = {f"{k}|{t}|{j}": n for (k, t, j), n in sorted(c.items())}
    settle = {}
    for col in ("judge_a", "judge_b"):
        f = [e[f"{col}_frames"] for e in ev_rows if e["truth"] is not None]
        settle[col] = {"median": float(np.median(f)), "p90": float(np.percentile(f, 90)), "max": int(max(f))}
    counts = {k: {"events": sum(e["kind"] == k for e in ev_rows), "with_truth": sum(e["kind"] == k and e["truth"] is not None for e in ev_rows),
                  "records": sum(r["kind"] == k for r in recs)} for k in KINDS}
    gv = {t: [e["truth_grip"] for e in ev_rows if e["truth"] == t] for t in ("held", "empty", "partial")}
    doc = {"request": 405, "params": SW.JUDGE, "grasp_z_max_mm": GRASP_Z_MAX, "counts": counts, "tables": tables, "settle_frames": settle,
           "truth_grip": {t: ({"n": len(v), "min": min(v), "p5": round(float(np.percentile(v, 5)), 2), "median": round(float(np.median(v)), 2),
                               "p95": round(float(np.percentile(v, 95)), 2), "max": max(v)} if v else {"n": 0}) for t, v in gv.items()},
           "lift_held_min": lift, "drops": drops, "events": ev_rows}
    OUT_JSON.write_text(json.dumps(doc, ensure_ascii=False, indent=1) + "\n")
    OUT_MD.write_text(markdown(doc))
    print(OUT_MD.read_text())


def markdown(doc):
    L = ["# 依頼 405: 握れたかの判定の境目と取り違え (記録から. analyze_405.py が書いた)", "",
         f"判定: 判定を始めて {SW.JUDGE['start']} コマ目以降に 続けて {SW.JUDGE['n']} コマの爪の読みの幅が {SW.JUDGE['w']} 以下で 落ち着いた とし, "
         f"その読みが {SW.JUDGE['held_min']}〜{SW.JUDGE['held_max']} = 挟んだ / {SW.JUDGE['empty_max']} 未満 = 空 / ほか・{SW.JUDGE['max_wait']} コマで落ち着かない = あいまい (空として扱う)", "",
         "## 数えた閉じ", "", "| 記録 | 本・回 | 閉じ (つかむ高さ) | 本当の答えのある閉じ |", "|---|---|---|---|"]
    for k in KINDS:
        c = doc["counts"][k]
        L.append(f"| {KIND_JA[k]} | {c['records']} | {c['events']} | {c['with_truth']} |")
    L += ["", "## 本当の答えごとの爪の読み (区間の最後の 5 コマの中央値)", "", "| 答え | 数 | 最小 | 5% | 中央値 | 95% | 最大 |", "|---|---|---|---|---|---|---|"]
    for t, v in doc["truth_grip"].items():
        if v.get("n"):
            L.append(f"| {t} | {v['n']} | {v['min']} | {v['p5']} | {v['median']} | {v['p95']} | {v['max']} |")
    names = {"judge_a": "(a) 指令が 20 を割ったコマから判定 (切り替え方式でコードが受け取るコマ)",
             "judge_b": "(b) 指令が 5 を割ったコマから判定", "fixed20": "比べ: 20 コマ後の読みだけで分ける (依頼 376 の決め方)"}
    for col, title in names.items():
        L += ["", f"## 取り違えの表 {title}", "", "| 記録 | 答え | 挟んだ | 空 | あいまい (→空) |", "|---|---|---|---|---|"]
        tb = doc["tables"][col]
        for k in KINDS:
            for t in ("held", "empty", "partial"):
                n = {j: tb.get(f"{k}|{t}|{j}", 0) for j in ("held", "empty", "ambiguous")}
                if sum(n.values()):
                    L.append(f"| {KIND_JA[k]} | {t} | {n['held']} | {n['empty']} | {n['ambiguous']} |")
        tot = Counter()
        for key, n in tb.items():
            _, t, j = key.split("|")
            tot[(t, j)] += n
        L.append(f"| **合計** | 挟んだのに 空・あいまい (→ 開く) | | | **{tot[('held', 'empty')] + tot[('held', 'ambiguous')]}** |")
        L.append(f"| **合計** | 空・中途なのに 挟んだ (→ 運ぶ) | **{tot[('empty', 'held')] + tot[('partial', 'held')]}** | | |")
        if col in doc["settle_frames"]:
            s = doc["settle_frames"][col]
            L.append(f"\n落ち着くまでのコマ: 中央値 {s['median']:g}・90% {s['p90']:g}・最大 {s['max']}")
    L += ["", "## 持ち上げの途中 (挟んだ閉じの 20〜60 コマ後の爪の読みの最小. 成功の回)", "", "| 記録 | 数 | 最小 | 中央値 | 最大 |", "|---|---|---|---|---|"]
    for k, v in doc["lift_held_min"].items():
        L.append(f"| {KIND_JA[k]} | {v['n']} | {v['min']} | {v['median']} | {v['max']} |")
    for d in doc["drops"]:
        L.append(f"\n「持ち上げで落とす」の回 {d['name']} ({d['kind']}) 閉じ {d['frame']} コマ目から 5 コマごと: 爪の読み {d['grip_every5']} / "
                 f"指令 {d['cmd_every5']} / 手先の高さ {d['tcp_z_every5']}")
    L += ["", "## 取り違えた閉じ ((a) の判定)", "", "| 記録 | 回 | コマ | 答え (読み) | 判定 (読み・コマ) |", "|---|---|---|---|---|"]
    for e in doc["events"]:
        if e["truth"] is None:
            continue
        bad = (e["truth"] == "held" and e["judge_a"] != "held") or (e["truth"] != "held" and e["judge_a"] == "held")
        if bad:
            L.append(f"| {e['kind']} | {e['name']} | {e['frame']} | {e['truth']} ({e['truth_grip']}) | {e['judge_a']} "
                     f"({e['judge_a_grip']}・{e['judge_a_frames']}) |")
    return "\n".join(L) + "\n"


if __name__ == "__main__":
    main()
