"""依頼 448 の 5: 机のカメラの絵で ブロックの見えている幅 (画素) を 実機と シム (一辺 21.7・446 の今の一辺 (est 23.5/23.7)・25) で比べる.
つかむ前のコマ (HOME と ブロックの上の始め. 腕がブロックに重ならないコマ) を 3 本 × 数コマ.
赤い所は yaw_lib_343 の机の読みと同じ取り方 (_components. HSV の赤. いちばん大きい塊). 読むだけ (どのファイルも変えない).

  幅: 赤い塊の 外接の回した長方形 (cv2.minAreaRect) の 長い辺・短い辺, 横 (u) と縦 (v) の外接の幅, 面積の平方根 (√面積)

使い方: python3 so101/sim/look_448/width_448.py [--frames 0,5,10,15,20,25,30]   → width_448.json・width_448.md・figs/width_448.png
"""
import argparse
import json
import sys
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parents[1]
sys.path.insert(0, str(SO101 / "ideal_var"))
import yaw_lib_343 as Y  # noqa: E402

EPS = ("ep00", "ep05", "ep03")
REAL = SO101 / "check_361"
SETS = {"実機": lambda ep, k: REAL / ep / "real" / f"{k:03d}_desk.png",
        "21.7": lambda ep, k: HERE / "render" / "b217" / ep / "blf" / f"{k:03d}_desk.png",
        "446": lambda ep, k: SO101 / "sim" / "look_446" / "render" / "SWC" / ep / "blf" / f"{k:03d}_desk.png",
        "25": lambda ep, k: HERE / "render" / "b25" / ep / "blf" / f"{k:03d}_desk.png"}


def measure(img):
    n, lab, st, cen = Y._components(img)
    if n <= 1:
        return None
    k = 1 + int(np.argmax(st[1:, cv2.CC_STAT_AREA]))
    m = (lab == k).astype(np.uint8)
    ys, xs = np.nonzero(m)
    pts = np.c_[xs, ys].astype(np.float32)
    (_, _), (w, h), _ = cv2.minAreaRect(pts)
    return {"area": int(m.sum()), "sqrt_area": round(float(np.sqrt(m.sum())), 2), "rect_long": round(float(max(w, h)), 2),
            "rect_short": round(float(min(w, h)), 2), "bbox_u": int(xs.max() - xs.min() + 1), "bbox_v": int(ys.max() - ys.min() + 1),
            "c": [round(float(xs.mean()), 1), round(float(ys.mean()), 1)]}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--frames", default="0,5,10,15,20,25,30")
    a = ap.parse_args()
    ks = [int(x) for x in a.frames.split(",")]
    sizes = {ep: json.loads((SO101 / "sim/look_388/poses/base" / ep / "poses.json").read_text())["block_size_mm"] for ep in EPS}
    rows = []
    for ep in EPS:
        for k in ks:
            r = {"ep": ep, "frame": k}
            for nm, f in SETS.items():
                p = f(ep, k)
                im = cv2.imread(str(p)) if p.exists() else None
                r[nm] = None if im is None else measure(im)
            rows.append(r)
    keys = ("sqrt_area", "rect_long", "rect_short", "bbox_u", "bbox_v")
    names = {"sqrt_area": "√面積", "rect_long": "回した長方形 長い辺", "rect_short": "回した長方形 短い辺", "bbox_u": "横の幅 (u)", "bbox_v": "縦の幅 (v)"}
    L = ["# 依頼 448 の 5: 机のカメラで見えているブロックの幅 (画素. 640×480. width_448.py が作る)\n",
         f"コマ: 3 本 × {ks} (HOME・ブロックの上の始め. 腕はブロックに重ならない). 446 の一辺 = 依頼 372 の当てはめ (ep00 {sizes['ep00']}・ep05 {sizes['ep05']}・ep03 {sizes['ep03']} mm)\n",
         "## 本ごとの中央 (画素)\n", "| 本 | 幅 | 実機 | シム 21.7 | シム 446 (est) | シム 25 | 実機 / 21.7 | 実機 / 446 | 実機 / 25 |", "|---|---|---|---|---|---|---|---|---|"]
    summ = {}
    for ep in EPS + ("全部",):
        rs = [r for r in rows if ep == "全部" or r["ep"] == ep]
        for kk in keys:
            v = {nm: [r[nm][kk] for r in rs if r[nm] and all(r[s] for s in SETS)] for nm in SETS}
            md = {nm: float(np.median(x)) if x else None for nm, x in v.items()}
            summ.setdefault(ep, {})[kk] = {nm: (round(x, 2) if x is not None else None) for nm, x in md.items()} | {"n": len(v["実機"])}
            ratio = lambda s: "—" if not md[s] else f"{md['実機'] / md[s]:.3f}"  # noqa: E731
            L.append(f"| {ep} | {names[kk]} | " + " | ".join("—" if md[nm] is None else f"{md[nm]:.1f}" for nm in SETS) +
                     f" | {ratio('21.7')} | {ratio('446')} | {ratio('25')} |")
    # 幅は一辺に比例するとして, 実機の √面積に合うシムの一辺 (21.7 と 25 の間の直線で)
    fit = {}
    for ep in EPS + ("全部",):
        s = summ[ep]["sqrt_area"]
        if s["21.7"] and s["25"]:
            a_ = (s["25"] - s["21.7"]) / (25.0 - 21.7)
            fit[ep] = round(21.7 + (s["実機"] - s["21.7"]) / a_, 2)
    L += ["", "## 実機の見えている幅に合うシムの一辺 (√面積が 21.7 と 25 の間で一辺に比例するとして. mm)\n",
          "| 本 | 合う一辺 |", "|---|---|"] + [f"| {ep} | {v} |" for ep, v in fit.items()]
    L += ["", "## コマごと (√面積. 画素)\n", "| 本 | コマ | " + " | ".join(SETS) + " |", "|---|---|" + "---|" * len(SETS)]
    for r in rows:
        L.append(f"| {r['ep']} | {r['frame']} | " + " | ".join("—" if not r[nm] else f"{r[nm]['sqrt_area']:.1f}" for nm in SETS) + " |")
    (HERE / "width_448.json").write_text(json.dumps({"frames": ks, "rows": rows, "median": summ, "fit_size_mm": fit}, ensure_ascii=False, indent=1))
    (HERE / "width_448.md").write_text("\n".join(L) + "\n")
    print("\n".join(L))
    # 並べ: 本ごとに コマ ks[0] のブロックのまわりを 4 倍に拡大 (左から 実機・21.7・446・25)
    tiles = []
    for ep in EPS:
        r = next(x for x in rows if x["ep"] == ep and x["frame"] == ks[0])
        c = np.array(r["実機"]["c"]).astype(int)
        row = []
        for nm, f in SETS.items():
            im = cv2.imread(str(f(ep, ks[0])))
            x0, y0 = max(c[0] - 30, 0), max(c[1] - 30, 0)
            crop = cv2.resize(im[y0:y0 + 60, x0:x0 + 60], (240, 240), interpolation=cv2.INTER_NEAREST)
            cv2.putText(crop, f"{ep} {'real' if nm == '実機' else nm}", (6, 18), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
            row.append(crop)
        tiles.append(np.hstack(row))
    (HERE / "figs").mkdir(exist_ok=True)
    cv2.imwrite(str(HERE / "figs" / "width_448.png"), np.vstack(tiles))


if __name__ == "__main__":
    main()
