"""依頼 362 のまとめ: check_362/<tag>/ (simreplay_362.py・features_362.py の出力) と 依頼 359 の推定置き (check_359/est. 読むだけ) を
依頼 353・359 と同じ測り方 (summary_353.one・gaps, summary_359.cause) で 全体・段階ごと・場所ごとに並べる → check_362/<name>.json・.md

使い方 (conda の lerobot 環境で): python so101/sim/summary_362.py --tags b_v2 [--name summary_362] [--eps 0,5,...]  (--eps は 本を絞って並べる)
"""

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
import summary_359 as U9  # noqa: E402

OUT = HERE.parent / "check_362"
C359 = HERE.parent / "check_359"


def where(tag):
    return (C359, "est") if tag == "359est" else (OUT, tag)


def load(tag, eps):
    d, t = where(tag)
    U3.OUT = d
    fr, ft, _, _ = U3.load(t)
    if eps is not None:
        fr = fr[fr["new_episode_index"].isin(eps)]
        if ft is not None:
            ft = ft[ft["new_episode_index"].isin(eps)] if "new_episode_index" in ft else ft[ft["episode"].isin(eps)]
    return fr, ft


def block(fr, ft):
    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()}
    return r


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--tags", required=True)
    ap.add_argument("--name", default="summary_362")
    ap.add_argument("--eps", default="")
    ap.add_argument("--no-359", action="store_true")
    a = ap.parse_args()
    eps = [int(x) for x in a.eps.split(",")] if a.eps else None
    tags = a.tags.split(",") + ([] if a.no_359 else ["359est"])
    scene = {r["plan_index"]: r for r in json.loads((C359 / "scene_359.json").read_text())["episodes"]}
    res = {}
    for t in tags:
        fr, ft = load(t, eps)
        if ft is not None:
            key = "new_episode_index" if "new_episode_index" in ft else "episode"
            ft = ft.copy()
            ft["place"] = ft[key].map(lambda i: scene[int(i)]["place"])
        r = block(fr, ft)
        r["by_place"] = {int(p): block(g, ft[ft["place"] == p] if ft is not None else None) for p, g in fr.groupby("place")}
        d, tt = where(t)
        U9.OUT = d
        r["cause"] = U9.cause(tt, scene) if eps is None else None
        res[t] = r
    nm = {"359est": "依頼 359 推定置き"}
    G = U3.GOAL
    f = U3.fmt
    L = [f"# 依頼 362 {a.name}", "", f"済みの条件: SigLIP {G['siglip']} 以上・赤の重心の差 机側 {G['desk_px']}px・手首 {G['wrist_px']}px 以内・"
         f"つかんでいる間の両方の爪のすき間 {G['gap_mm']}mm 以内の割合 1.0" + (f". 本: {a.eps}" if eps else ""), "",
         "## 全体", "", "| | " + " | ".join(nm.get(c, c) for c in tags) + " |", "|---|" + "---|" * len(tags)]
    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),
                           ("明るさの差 L 机側 (シム−実機)", "desk", "L_diff", 1), ("明るさの差 L 手首", "wrist", "L_diff", 1)):
        L.append(f"| {lab} | " + " | ".join(f(res[c][cam]["all"].get(k), n) for c in tags) + " |")
    L.append("| 爪のすき間 1mm 以内の割合 | " + " | ".join(f(res[c]["gaps"].get("within_1mm_frac"), 3) for c in tags) + " |")
    L.append("| 本数 | " + " | ".join(str(res[c]["episodes"]) for c in tags) + " |")
    for cam, cj in (("desk", "机側"), ("wrist", "手首")):
        L += ["", f"## 段階ごと ({cj}): SigLIP / 赤の重心の差 px", "", "| 段階 | " + " | ".join(nm.get(c, c) for c in tags) + " |",
              "|---|" + "---|" * len(tags)]
        for s in U.STAGE_ORDER:
            L.append(f"| {U.STAGE_JA[s]} | " + " | ".join(
                f"{f(res[c][cam]['by_stage'].get(s, {}).get('siglip'), 3)} / {f(res[c][cam]['by_stage'].get(s, {}).get('red_px_median'), 1)}"
                for c in tags) + " |")
    L += ["", "## 段階ごと 爪のすき間 1mm 以内の割合", "", "| 段階 | " + " | ".join(nm.get(c, 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"{f(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 += ["", "## 場所ごと: SigLIP 机側 / 手首, 赤の重心の差 机側 / 手首 px, 爪のすき間 1mm 以内", "",
          "| 場所 | " + " | ".join(nm.get(c, c) for c in tags) + " |", "|---|" + "---|" * len(tags)]
    for p in sorted(res[tags[0]]["by_place"]):
        cells = []
        for c in tags:
            b = res[c]["by_place"].get(p)
            cells.append("-" if b is None else
                         f"{f(b['desk']['all'].get('siglip'), 3)} / {f(b['wrist']['all'].get('siglip'), 3)}, "
                         f"{f(b['desk']['all'].get('red_px_median'))} / {f(b['wrist']['all'].get('red_px_median'))}, "
                         f"{f(b['gaps'].get('within_1mm_frac'), 3)} ({b['episodes']} 本)")
        L.append(f"| 場所{p} | " + " | ".join(cells) + " |")
    if eps is None:
        L += ["", "## 手首の赤の重心の差の区間ごと (summary_359 と同じ分け方)", "", "| 区間 | " + " | ".join(nm.get(c, c) for c in tags) + " |",
              "|---|" + "---|" * len(tags)]
        for ph, pj in U9.PHASES:
            cells = []
            for c in tags:
                s = res[c]["cause"]["phases"].get(ph, {})
                cells.append("-" if not s.get("frames") else
                             f"{f(s['dist_median'])} px ({s['direction']}. 15px 以内 {f(s['within15_frac'] * 100, 0)}%)")
            L.append(f"| {pj} | " + " | ".join(cells) + " |")
        L += ["", "### 場所ごと: 手首の赤の重心の差 px 机の上 / 爪の中", "", "| 場所 | " + " | ".join(nm.get(c, c) for c in tags) + " |",
              "|---|" + "---|" * len(tags)]
        for p in sorted(res[tags[0]]["cause"]["by_place"]):
            cells = []
            for c in tags:
                s = res[c]["cause"]["by_place"].get(p, {})
                cells.append(f"{f(s.get('table', {}).get('dist_median'))} ({s.get('table', {}).get('direction', '-')}) / "
                             f"{f(s.get('held', {}).get('dist_median'))} ({s.get('held', {}).get('direction', '-')})")
            L.append(f"| 場所{p} | " + " | ".join(cells) + " |")
        L += ["", "### 手首の回転 (符号つき) と 差の向きの相関 (本ごとの中央値)", ""]
        for c in tags:
            L.append(f"- {nm.get(c, 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_362.py (依頼 362)", "goal": G, "eps": eps, "tags": res},
                                                   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()
