"""依頼 359 のまとめ: check_359/<tag>/ (simreplay_359.py・features_359.py の出力) を
依頼 353・355 と同じ測り方 (summary_353.one・gaps) で並べ, 手首の赤の重心の差の原因分けの表を足す → check_359/summary_359.json・.md
古い 5 本 (依頼 355 の level 8. check_355/t_lv8.json と check_355/lv8/ のコマの表) は読むだけ.

  手首の差の分け方 (両方に赤が 1000px 以上のコマ. 差 = シム − 実機. 右 = +x, 下 = +y):
    机の上 = 段階「ブロックの上」(つかみ始める前. ブロックは机に置いたまま)
    つかむ = 段階「つかむ」(閉じる途中. ブロックは置いた所から爪の間へ動く)
    爪の中 = 爪がつかんでいる間 (held) の「持ち上げ」「箱の上」
  机の上で 足して見るもの:
    形だけの差 (凸包の重心 − 実機の赤の重心. 爪で隠れた分を除いた差), 関節のずれを入れない (0) ときの形だけの差
    手首から逆に出したブロックの位置 (implied) − 置いた位置 (mm), 1 本の中での implied のばらつき (腕の姿勢で動くか)

使い方 (conda の lerobot 環境で): python so101/sim/summary_359.py --tags plan,est
"""

import argparse
import json
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import summary_353 as U3  # noqa: E402
import summary_334 as U  # noqa: E402

OUT = HERE.parent / "check_359"
C355 = HERE.parent / "check_355"
MIN_PX = U.RED_MIN_PX["wrist"]
PHASES = (("table", "机の上 (ブロックの上)"), ("grasp", "つかむ (閉じる途中)"), ("held", "爪の中 (持ち上げ・箱の上)"),
          ("after", "離す・戻る"))


def fmt(x, n=1):
    return U3.fmt(x, n)


def phase_of(d):
    ph = np.full(len(d), "", object)
    st, h = d["stage"].to_numpy(), d["held"].to_numpy()
    ph[st == "ABOVE_BLOCK"] = "table"
    ph[st == "GRASP"] = "grasp"
    ph[(h == 1) & np.isin(st, ("LIFT", "ABOVE_BOX"))] = "held"
    ph[np.isin(st, ("RELEASE", "RETURN"))] = "after"
    return ph


def both(d):
    return d[(d["wrist_red_real_px"] >= MIN_PX) & (d["wrist_red_sim_px"] >= MIN_PX)].copy()


def dir_text(dx, dy):
    """シムの赤が 実機に対して どちらにあるか (画面で)."""
    out = []
    if abs(dx) >= 3:
        out.append(f"{'右' if dx > 0 else '左'} {abs(dx):.0f}")
    if abs(dy) >= 3:
        out.append(f"{'下' if dy > 0 else '上'} {abs(dy):.0f}")
    return "・".join(out) if out else "ほぼ 0"


def stat(g, extra=True):
    if not len(g):
        return {"frames": 0}
    dx = g["wrist_red_sim_cx"] - g["wrist_red_real_cx"]
    dy = g["wrist_red_sim_cy"] - g["wrist_red_real_cy"]
    out = {"frames": int(len(g)), "episodes": int(g["new_episode_index"].nunique()),
           "dist_median": round(float(g["wrist_red_dist_px"].median()), 1),
           "dist_p90": round(float(g["wrist_red_dist_px"].quantile(0.9)), 1),
           "dx_median": round(float(dx.median()), 1), "dy_median": round(float(dy.median()), 1),
           "within15_frac": round(float((g["wrist_red_dist_px"] <= 15).mean()), 3),
           "area_ratio_median": round(float(g["wrist_red_area_ratio"].median()), 2)}
    out["direction"] = dir_text(out["dx_median"], out["dy_median"])
    # 本ごとの中央値の dx・dy の向きのそろい方 (本ごとに同じ向きか)
    pe = g.assign(dx=dx, dy=dy).groupby("new_episode_index")[["dx", "dy"]].median()
    out["ep_dx_median_p10_p90"] = [round(float(pe["dx"].quantile(q)), 1) for q in (0.1, 0.5, 0.9)]
    out["ep_dy_median_p10_p90"] = [round(float(pe["dy"].quantile(q)), 1) for q in (0.1, 0.5, 0.9)]
    if extra and "wrist_hull_cx" in g:
        hx, hy = g["wrist_hull_cx"] - g["wrist_red_real_cx"], g["wrist_hull_cy"] - g["wrist_red_real_cy"]
        out["hull_dist_median"] = round(float(np.hypot(hx, hy).median()), 1)
        out["hull_dx_median"], out["hull_dy_median"] = round(float(hx.median()), 1), round(float(hy.median()), 1)
        if g["wrist_hull0_cx"].notna().any():
            h0x, h0y = g["wrist_hull0_cx"] - g["wrist_red_real_cx"], g["wrist_hull0_cy"] - g["wrist_red_real_cy"]
            ok = h0x.notna()
            out["hull0_dist_median"] = round(float(np.hypot(h0x[ok], h0y[ok]).median()), 1)
            out["hull0_dx_median"], out["hull0_dy_median"] = round(float(h0x[ok].median()), 1), round(float(h0y[ok].median()), 1)
    return out


def implied(g, scene, how):
    """机の上のコマの 手首から出した位置 − 置いた位置 (mm). 本ごとの中央値と, 1 本の中のばらつき."""
    rows = []
    for i, e in g.dropna(subset=["implied_x_mm"]).groupby("new_episode_index"):
        b = scene[i][how]["xy"]
        ix, iy = e["implied_x_mm"].to_numpy(), e["implied_y_mm"].to_numpy()
        est = scene[i]["est"]["xy"]
        rows.append({"ep": int(i), "dx": float(np.median(ix) - b[0]), "dy": float(np.median(iy) - b[1]),
                     "dx_est": float(np.median(ix) - est[0]), "dy_est": float(np.median(iy) - est[1]),
                     "spread": float(np.hypot(np.percentile(ix, 90) - np.percentile(ix, 10), np.percentile(iy, 90) - np.percentile(iy, 10))),
                     "n": int(len(e))})
    if not rows:
        return {}
    a = {k: np.array([r[k] for r in rows]) for k in rows[0]}
    return {"episodes": len(rows),
            "minus_placed_mm_median": [round(float(np.median(a["dx"])), 1), round(float(np.median(a["dy"])), 1)],
            "minus_placed_dist_mm_median": round(float(np.median(np.hypot(a["dx"], a["dy"]))), 1),
            "minus_est_mm_median": [round(float(np.median(a["dx_est"])), 1), round(float(np.median(a["dy_est"])), 1)],
            "minus_est_dist_mm_median": round(float(np.median(np.hypot(a["dx_est"], a["dy_est"]))), 1),
            "spread_in_episode_mm_median": round(float(np.median(a["spread"])), 1),
            "spread_in_episode_mm_p90": round(float(np.percentile(a["spread"], 90)), 1)}


def roll_bin(r):
    r = abs(r)
    return "0〜15°" if r < 15 else ("15〜30°" if r < 30 else ("30〜45°" if r < 45 else "45° 以上"))


def cause(tag, scene):
    import pandas as pd
    fr = pd.concat([pd.read_csv(f) for f in sorted((OUT / tag).glob("ep*_frames.csv"))], ignore_index=True)
    fr["phase"] = phase_of(fr)
    b = both(fr)
    res = {"phases": {p: stat(b[b["phase"] == p]) for p, _ in PHASES}}
    res["all"] = stat(b, extra=False)
    t = b[b["phase"] == "table"]
    res["implied"] = implied(fr[(fr["stage"] == "ABOVE_BLOCK") & (fr["wrist_red_real_px"] >= MIN_PX)], scene, "plan" if tag != "est" else "est")
    # 場所ごと・手首の回転の大きさごと (本ごとの つかむ所の手首の回転 = 段階「ブロックの上」の最後のコマの state)
    roll = fr[fr["stage"] == "ABOVE_BLOCK"].groupby("new_episode_index")["wrist_roll_deg"].last()
    b["roll_bin"] = b["new_episode_index"].map(lambda i: roll_bin(roll.get(i, 0.0)))
    res["by_place"] = {int(p): {ph: stat(g[g["phase"] == ph], extra=False) for ph in ("table", "held")} for p, g in b.groupby("place")}
    res["by_roll"] = {rb: {ph: stat(g[g["phase"] == ph], extra=False) for ph in ("table", "held")}
                      for rb, g in sorted(b.groupby("roll_bin"), key=lambda kv: ["0〜15°", "15〜30°", "30〜45°", "45° 以上"].index(kv[0]))}
    # 手首の回転 (符号つき) と 差の向きの相関 (本ごとの中央値)
    pe = b.assign(dx=b["wrist_red_sim_cx"] - b["wrist_red_real_cx"], dy=b["wrist_red_sim_cy"] - b["wrist_red_real_cy"])
    for ph in ("table", "held"):
        q = pe[pe["phase"] == ph].groupby("new_episode_index")[["dx", "dy"]].median().join(roll)
        if len(q) > 3:
            res[f"corr_roll_{ph}"] = {"dx": round(float(np.corrcoef(q["wrist_roll_deg"], q["dx"])[0, 1]), 2),
                                      "dy": round(float(np.corrcoef(q["wrist_roll_deg"], q["dy"])[0, 1]), 2)}
    res["places_count"] = {int(p): int(n) for p, n in fr.groupby("place")["new_episode_index"].nunique().items()}
    res["table_episodes"] = int(t["new_episode_index"].nunique())
    return res


def cause_old():
    """古い 5 本 (依頼 355 level 8) の 同じ分け方 (形だけの差・関節 0 は無い)."""
    import pandas as pd
    fr = pd.concat([pd.read_csv(f) for f in sorted((C355 / "lv8").glob("ep*_frames.csv"))], ignore_index=True)
    fr["phase"] = phase_of(fr)
    b = both(fr)
    return {"phases": {p: stat(b[b["phase"] == p], extra=False) for p, _ in PHASES}, "all": stat(b, extra=False)}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--tags", default="plan,est")
    ap.add_argument("--name", default="summary_359")
    a = ap.parse_args()
    tags = a.tags.split(",")
    U3.OUT = OUT
    scene = {r["plan_index"]: r for r in json.loads((OUT / "scene_359.json").read_text())["episodes"]}
    res = {}
    for t in tags:
        fr, ft, _, _ = U3.load(t)
        r = {"episodes": int(fr["new_episode_index"].nunique()), "frames": int(len(fr))}
        for cam in ("desk", "wrist"):
            r[cam] = {"all": U3.one(fr, ft, cam), "by_stage": {s: U3.one(fr, ft, cam, s) for s in U.STAGE_ORDER if (fr["stage"] == s).any()}}
        r["gaps"] = U3.gaps(fr)
        r["gaps_by_stage"] = {s: U3.gaps(fr[fr["stage"] == s]) for s in U.STAGE_ORDER if ((fr["stage"] == s) & (fr["held"] == 1)).any()}
        r["cause"] = cause(t, scene)
        res[t] = r
    old = json.loads((C355 / "t_lv8.json").read_text())["tags"]["lv8"]
    old["cause"] = cause_old()
    cols = tags + ["old5"]
    R_ = dict(res, old5=old)
    nm = {"plan": "新 50 本 割り振りで置く", "est": "新 50 本 推定で置く", "old5": "古い 5 本 (依頼 355 lv8)"}
    G = U3.GOAL
    L = [f"# 依頼 359 {a.name}", "", f"済みの条件: SigLIP {G['siglip']} 以上・赤の重心の差 机側 {G['desk_px']}px・手首 {G['wrist_px']}px 以内・"
         f"つかんでいる間の両方の爪のすき間 {G['gap_mm']}mm 以内の割合 1.0", "",
         "場所ごとの本数: " + "・".join(f"場所{p} {n} 本" for p, n in res[tags[0]]["cause"]["places_count"].items()), "",
         "## 済みの条件の 3 つ (全体)", "", "| | " + " | ".join(nm[c] for c in cols) + " |", "|---|" + "---|" * len(cols)]
    for lab, cam, k, n in (("SigLIP 机側", "desk", "siglip", 3), ("SigLIP 手首", "wrist", "siglip", 3),
                           ("赤の重心の差 机側 px (中央値)", "desk", "red_px_median", 1), ("赤の重心の差 手首 px (中央値)", "wrist", "red_px_median", 1),
                           ("SSIM 机側", "desk", "ssim", 3), ("SSIM 手首", "wrist", "ssim", 3),
                           ("明るさの差 L 机側 (シム−実機)", "desk", "L_diff", 1), ("明るさの差 L 手首", "wrist", "L_diff", 1)):
        L.append(f"| {lab} | " + " | ".join(fmt(R_[c][cam]["all"].get(k), n) for c in cols) + " |")
    L.append("| 爪のすき間 1mm 以内の割合 | " + " | ".join(fmt(R_[c]["gaps"].get("within_1mm_frac"), 3) for c in cols) + " |")
    L.append("| 本数 | " + " | ".join(str(R_[c].get("episodes") if c != "old5" else len(old["episodes"])) for c in cols) + " |")
    for cam, cj in (("desk", "机側"), ("wrist", "手首")):
        L += ["", f"## 段階ごと ({cj}): SigLIP / 赤の重心の差 px (中央値)", "", "| 段階 | " + " | ".join(nm[c] for c in cols) + " |",
              "|---|" + "---|" * len(cols)]
        for s in U.STAGE_ORDER:
            cells = []
            for c in cols:
                b = R_[c][cam]["by_stage"].get(s, {})
                cells.append(f"{fmt(b.get('siglip'), 3)} / {fmt(b.get('red_px_median'), 1)}")
            L.append(f"| {U.STAGE_JA[s]} | " + " | ".join(cells) + " |")
    L += ["", "## 段階ごと 爪のすき間 1mm 以内の割合 (つかんでいる間のコマ)", "", "| 段階 | " + " | ".join(nm[c] for c in tags) + " |",
          "|---|" + "---|" * len(tags)]
    for s in U.STAGE_ORDER:
        if any(s in res[c]["gaps_by_stage"] for c in tags):
            L.append(f"| {U.STAGE_JA[s]} | " + " | ".join(
                f"{fmt(res[c]['gaps_by_stage'].get(s, {}).get('within_1mm_frac'), 3)} ({res[c]['gaps_by_stage'].get(s, {}).get('held_frames', 0)} コマ)"
                for c in tags) + " |")
    L += ["", "## 手首の赤の重心の差の原因分け (両方に赤が 1000px 以上のコマ. 向きは シムの赤が実機に対して どちらにあるか)", "",
          "| 区間 | " + " | ".join(nm[c] for c in cols) + " |", "|---|" + "---|" * len(cols)]
    for p, pj in PHASES:
        cells = []
        for c in cols:
            s = R_[c]["cause"]["phases"].get(p, {})
            cells.append("-" if not s.get("frames") else
                         f"{fmt(s['dist_median'])} px ({s['direction']}. 15px 以内 {fmt(s['within15_frac'] * 100, 0)}%. {s['frames']} コマ)")
        L.append(f"| {pj} | " + " | ".join(cells) + " |")
    L += ["", "### 机の上: 形だけの差 (爪の隠れを除く) と 関節のずれを入れないとき (形だけ)", "",
          "| | " + " | ".join(nm[c] for c in tags) + " |", "|---|" + "---|" * len(tags)]
    for lab, k, kx, ky in (("赤の重心 (今)", "dist_median", "dx_median", "dy_median"),
                           ("形だけ (今の関節のずれ)", "hull_dist_median", "hull_dx_median", "hull_dy_median"),
                           ("形だけ (関節のずれ 0)", "hull0_dist_median", "hull0_dx_median", "hull0_dy_median")):
        cells = []
        for c in tags:
            s = res[c]["cause"]["phases"]["table"]
            cells.append(f"{fmt(s.get(k))} px ({dir_text(s.get(kx, 0), s.get(ky, 0))})" if s.get(k) is not None else "-")
        L.append(f"| {lab} | " + " | ".join(cells) + " |")
    for lab, ph in (("爪の中", "held"),):
        cells = []
        for c in tags:
            s = res[c]["cause"]["phases"][ph]
            cells.append(f"{fmt(s.get('hull_dist_median'))} px ({dir_text(s.get('hull_dx_median', 0), s.get('hull_dy_median', 0))})")
        L.append(f"| {lab}: 形だけ | " + " | ".join(cells) + " |")
    L += ["", "### 机の上: 手首の赤から逆に出したブロックの位置 (シムの腕・カメラのまま)", "",
          "| | " + " | ".join(nm[c] for c in tags) + " |", "|---|" + "---|" * len(tags)]
    for lab, k in (("− 置いた位置 (x, y mm. 本ごとの中央値の中央値)", "minus_placed_mm_median"), ("同 距離 mm", "minus_placed_dist_mm_median"),
                   ("− 机側からの推定 (x, y mm)", "minus_est_mm_median"), ("同 距離 mm", "minus_est_dist_mm_median"),
                   ("1 本の中のばらつき mm (10〜90%. 中央値)", "spread_in_episode_mm_median"), ("同 (本の 90%)", "spread_in_episode_mm_p90")):
        L.append(f"| {lab} | " + " | ".join(fmt(res[c]["cause"]["implied"].get(k)) if not isinstance(res[c]["cause"]["implied"].get(k), list)
                                             else str(res[c]["cause"]["implied"][k]) for c in tags) + " |")
    for key, title, groups in (("by_place", "場所ごと", None), ("by_roll", "つかむ所の手首の回転の大きさごと", None)):
        L += ["", f"### {title}: 手首の赤の重心の差 px 中央値 (向き) 机の上 / 爪の中 (本数)", "", "| | " + " | ".join(nm[c] for c in tags) + " |",
              "|---|" + "---|" * len(tags)]
        ks = list(res[tags[0]]["cause"][key].keys())
        for g in ks:
            cells = []
            for c in tags:
                s = res[c]["cause"][key].get(g, {})
                a_, b_ = s.get("table", {}), s.get("held", {})
                cells.append(f"{fmt(a_.get('dist_median'))} ({a_.get('direction', '-')}) / {fmt(b_.get('dist_median'))} ({b_.get('direction', '-')}) "
                             f"({max(a_.get('episodes', 0), b_.get('episodes', 0))} 本)")
            L.append(f"| {('場所' + str(g)) if key == 'by_place' else g} | " + " | ".join(cells) + " |")
    L += ["", "### 手首の回転 (符号つき) と 差の向きの相関 (本ごとの中央値)", ""]
    for c in tags:
        L.append(f"- {nm[c]}: 机の上 {res[c]['cause'].get('corr_roll_table')}・爪の中 {res[c]['cause'].get('corr_roll_held')}")
    (OUT / f"{a.name}.json").write_text(json.dumps({"made_by": "so101/sim/summary_359.py (依頼 359)", "goal": G, "tags": res,
                                                    "old5_lv8": {k: old[k] for k in ("episodes", "desk", "wrist", "gaps", "cause")}},
                                                   ensure_ascii=False, indent=1, default=str))
    (OUT / f"{a.name}.md").write_text("\n".join(L) + "\n")
    print("\n".join(L))


if __name__ == "__main__":
    main()
