"""依頼 367: 比べる 5 本で level 8 と level 9 を並べる → check_367/compare_367.md・json
- SigLIP・明るさの差 L・赤の重心の差: check_367/<tag>/ (simreplay_367 + features_367) を summary_353 と同じ測り方で (全体・段階ごと)
- 箱の影・腕の影・影の地図の差: check_367/tune/m_<shadow_tag>.csv (tune_light_367 を 比べる 5 本で走らせたもの) と 実機

使い方 (conda の lerobot 環境で): python so101/sim/compare_367.py --tags lv8,lv9 --shadow cmp
"""

import argparse
import json
import sys
from pathlib import Path

import pandas as pd

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

OUT = Y7.OUT
SH = [("boxsh_down_depth", "箱の影 下 濃さ", 3), ("boxsh_down_len", "箱の影 下 長さ px", 1), ("boxsh_down_width", "箱の影 下 ぼけ幅 px", 1),
      ("boxsh_right_depth", "箱の影 右 濃さ", 3), ("boxsh_right_len", "箱の影 右 長さ px", 1), ("boxsh_right_width", "箱の影 右 ぼけ幅 px", 1),
      ("armsh_depth", "腕の影 濃さ (机側)", 3), ("armsh_width", "腕の影 ぼけ幅の目安 px", 1), ("map_diff", "影の地図の差 L (机側)", 2),
      ("inner_L", "箱の内側の L (机側)", 1), ("floor_top_minus_bottom", "箱の底 上 − 下 の L", 1),
      ("wrist_p10_p50", "手首 机の L 10%÷50% (影の濃さの目安)", 3)]


def shadows(tag, real_csv):
    rr, sm = pd.read_csv(real_csv), pd.read_csv(OUT / "tune" / f"m_{tag}.csv")
    keyc = ["ep", "frame"]
    ok = rr[rr["box_clear"] == 1][keyc]

    def med(df, c):
        if c not in df:
            return None
        d = df.merge(ok, on=keyc) if (c.startswith("box") or c in ("inner_L", "floor_top_minus_bottom")) else df
        return float(d[c].median())
    out = {"real": {c: med(rr, c) for c, _, _ in SH}}
    for nm, g in sm.groupby("set", sort=False):
        out[nm] = {c: med(g, c) for c, _, _ in SH}
    out["_frames"] = {"all": int(len(rr)), "box_clear": int(len(ok))}
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--tags", default="lv8,lv9")
    ap.add_argument("--shadow", default="cmp")
    ap.add_argument("--real", default="")
    a = ap.parse_args()
    tags = a.tags.split(",")
    eps = Y7.COMPARE_EPS
    U3.OUT = OUT
    res = {}
    for t in tags:
        fr, ft = U3.load(t)[:2]
        fr = fr[fr["new_episode_index"].isin(eps)]
        ft = ft[ft["new_episode_index"].isin(eps)] if "new_episode_index" in ft else ft[ft["episode"].isin(eps)]
        r = {}
        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["by_ep"] = {int(i): {cam: U3.one(g, ft[ft[("new_episode_index" if "new_episode_index" in ft else "episode")] == i], cam)
                               for cam in ("desk", "wrist")} for i, g in fr.groupby("new_episode_index")}
        res[t] = r
    real_csv = Path(a.real) if a.real else OUT / "tune" / f"real_s5_{'-'.join(map(str, eps))}.csv"
    sh = shadows(a.shadow, real_csv)
    f = U3.fmt
    L = ["# 依頼 367 比べる 5 本 (割り振り " + ",".join(map(str, eps)) + "): level 8 と level 9", "",
         "箱 = box_365.json・見た目の回 v2・爪の中 b・ブロック 推定置き (依頼 362 と同じ). 違うのは 光だけ.", "",
         "## SigLIP・明るさ・赤の重心", "", "| | " + " | ".join(tags) + " |", "|---|" + "---|" * len(tags)]
    for lab, cam, k, n in (("SigLIP 机側", "desk", "siglip", 3), ("SigLIP 手首", "wrist", "siglip", 3),
                           ("明るさの差 L 机側 (シム−実機)", "desk", "L_diff", 2), ("明るさの差 L 手首", "wrist", "L_diff", 2),
                           ("赤の重心の差 机側 px", "desk", "red_px_median", 1), ("赤の重心の差 手首 px", "wrist", "red_px_median", 1)):
        L.append(f"| {lab} | " + " | ".join(f(res[t][cam]["all"].get(k), n) for t in tags) + " |")
    for cam, cj in (("desk", "机側"), ("wrist", "手首")):
        L += ["", f"### 段階ごと ({cj}): SigLIP / 明るさの差 L", "", "| 段階 | " + " | ".join(tags) + " |", "|---|" + "---|" * len(tags)]
        for s in U.STAGE_ORDER:
            L.append(f"| {U.STAGE_JA[s]} | " + " | ".join(
                f"{f(res[t][cam]['by_stage'].get(s, {}).get('siglip'), 3)} / {f(res[t][cam]['by_stage'].get(s, {}).get('L_diff'), 1)}"
                for t in tags) + " |")
    L += ["", "### 本ごと: SigLIP 机側 / 手首", "", "| 本 | " + " | ".join(tags) + " |", "|---|" + "---|" * len(tags)]
    for i in eps:
        L.append(f"| {i} | " + " | ".join(f"{f(res[t]['by_ep'].get(i, {}).get('desk', {}).get('siglip'), 3)} / "
                                          f"{f(res[t]['by_ep'].get(i, {}).get('wrist', {}).get('siglip'), 3)}" for t in tags) + " |")
    cols = [c for c in sh if c not in ("_frames",)]
    L += ["", f"## 影 (机側. 5 コマおき {sh['_frames']['all']} コマ. 箱の影・箱の内側は 腕が箱から 60px 以内に来ないコマ {sh['_frames']['box_clear']} コマ. 中央値)", "",
          "| | " + " | ".join(cols) + " |", "|---|" + "---|" * len(cols)]
    for c, lab, n in SH:
        L.append(f"| {lab} | " + " | ".join(f(sh[k].get(c), n) for k in cols) + " |")
    (OUT / "compare_367.json").write_text(json.dumps({"made_by": "so101/sim/compare_367.py (依頼 367)", "eps": eps, "tags": res, "shadows": sh},
                                                     ensure_ascii=False, indent=1, default=str))
    (OUT / "compare_367.md").write_text("\n".join(L) + "\n")
    print("\n".join(L))


if __name__ == "__main__":
    main()
