"""依頼 364: render_364.py の絵に post_361.Post と同じ歪み・くせ・明るさの倍率を足して 640×480 にし, 光の形に関わる所を
実機・依頼 363 (v2)・依頼 364 で測る.

測るもの (ラベルの絵は 依頼 363 の bl363_lab. 箱は 80×80mm. 実機の箱は 机側の絵で (−7, −11)px ずれている (依頼 363 の box_edges) ので
実機に当てる箱のマスクだけ その分ずらす):
- 机のむら (机側): 机の画素 (腕・箱・ブロックのまわり 6px を除く) を 8×6 の格子に分け, 格子ごとの L の中央値の ばらつき (標準偏差).
  格子の差 = 実機と同じ格子で (格子 − 絵の平均) の差の絶対値の平均
- 箱のまわりの明るい輪 (机側): 箱から 8〜40px の机 (パネルの側 = 絵の左上の半分) の L − 箱から 80〜160px の机の L
- 箱の影 (机側): 箱の下の辺・右の辺から外へ 0〜70px の L の形 (辺に沿って中央値. ケーブルなど細い暗い物は消す). 濃さ = 影の芯 ÷ 外の端 10px の机,
  長さ・ぼけ幅 = shadow_of_profile. 腕が箱から 60px 以内に来ないコマ
- 腕の影 (机側): 腕から 5〜80px の机 (箱・ブロックのまわりを除く) の L の 5% 点 ÷ 机の中央値 (濃さ).
  ぼけ幅 = 1.02 × (机の中央値 − 5% 点) ÷ 明るさの傾きの 98% 点 (σ 1.5px でならした L. ぼけたふちの 10→90% の幅に当たる).
  ケーブル (実機だけにある) は 9px の閉じで消してから
- 影の地図の差 (机側): 腕・箱から 100px 以内の机で (σ 2px でならした L の 実機との差 − その中央値) の 二乗平均の根
- 箱の内側 (机側): 底の内側と内の壁 を合わせた所の外接の四角を 4×4 に分けた L の中央値. 実機との相関・差
- ブロックのまわりの赤み (机側・手首): 赤の所を 3〜12px 広げた輪 ∩ 机 の a* − 机全体の a* (依頼 353 の faces と同じ)
- ブロックの光の斑点: 赤の所の L の 98%・99.5% 点・L が 70 を超える画素の割合 と 面ごとの L (依頼 363 の post_363.regions)

使い方 (conda の lerobot 環境で):
    python so101/blender/post_364.py --make-tex 40                         # → check_364/_tex/table_flat_s40.png
    python so101/blender/post_364.py --make-tex-fit tune01:p1              # → check_364/_tex/table_fit_p1.png
    python so101/blender/post_364.py --fit-gain tune01 --var p1 [--frames 0,5]
    python so101/blender/post_364.py --finish tune01 --var p1
    python so101/blender/post_364.py --measure tune01 --vars 363,p1 --tag t1   # → check_364/m_<tag>.csv
    python so101/blender/post_364.py --summ t1                              # 表を出す
"""

import argparse
import csv
import json
import sys
from pathlib import Path

import cv2
import numpy as np
import pandas as pd

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
sys.path.insert(0, str(HERE))
import post_361 as P1  # noqa: E402
import post_363 as P3  # noqa: E402
import measure_scene_330 as MS  # noqa: E402

OUT = SO101 / "check_364"
C361, C363 = SO101 / "check_361", SO101 / "check_363"
S = 32
L_TABLE, L_ARM, L_SERVO, L_BLOCK, L_BOXF, L_BOXW, L_JAW, L_BOXO, L_BOXR = P3.L_TABLE, P3.L_ARM, P3.L_SERVO, P3.L_BLOCK, P3.L_BOXF, \
    P3.L_BOXW, P3.L_JAW, P3.L_BOXO, P3.L_BOXR
BOX = (L_BOXF, L_BOXW, L_BOXO, L_BOXR)
ARM = (L_ARM, L_SERVO, L_JAW)
REAL_BOX_SHIFT = (-7, -11)  # 依頼 363 box_edges_363.json (20 コマとも (−7〜−9, −9〜−11))


def src_of(ep):
    return P3.src_of(ep)


def frames_of(ep):
    return P3.frames_of(ep)


def sim_path(ep, var, k, cam):
    if var == "363":
        return C363 / ep / f"blf_v2_s{S}" / f"{k:03d}_{cam}.png"
    return OUT / ep / f"blf_{var}_s{S}" / f"{k:03d}_{cam}.png"


def gain_path(var):
    return OUT / f"gain_{var}.json"


# ---- 机に貼る絵 -------------------------------------------------------------------------------

def make_tex(sigma):
    """look.json の机の絵 (実機の机側の背景を机の面に写したもの) から 大きなむら (σ mm でぼかした絵) を割って 平らにする.
    小さな模様 (しみ・点) は残す. 平均の明るさは 写った所 (マスク 255) の平均のまま."""
    look = json.loads((C361 / "scene" / "look.json").read_text())
    tex = cv2.imread(look["table_texture"]).astype(np.float32)
    mk = cv2.imread(str(SO101 / "check_337" / "table_texture_pos1b_mask.png"), 0) == 255
    w = cv2.GaussianBlur(mk.astype(np.float32), (0, 0), sigma)
    low = cv2.GaussianBlur(tex * mk[..., None], (0, 0), sigma) / np.maximum(w, 1e-3)[..., None]
    mean = tex[mk].mean(0)
    out = np.where(mk[..., None], tex / np.maximum(low, 1) * mean, mean)
    (OUT / "_tex").mkdir(parents=True, exist_ok=True)
    p = OUT / "_tex" / f"table_flat_s{sigma}.png"
    cv2.imwrite(str(p), np.clip(out + 0.5, 0, 255).astype(np.uint8))
    print(p, "mean", mean.round(1))


def make_tex_fit(ep, var, sigma_px=25, base="table_flat_s40.png"):
    """平らにした机の絵 (base) × 大きなむらの直し C. C = 当てはめの本 (ep) を var で描いた机側の絵での
    (実機の灰色 ÷ Blender の灰色) を 机の画素だけで σ px にならし (腕・ブロックから 25px・箱から 80px (箱の影) は除く), コマの中央値をとり,
    σ 50px でならして 1 つのなめらかな面にして 机の面 (1px = 1mm) に写したもの.
    実機の机側の絵の 大きなむら (カメラの周辺の暗さ・照明の当たり方) を 机の絵に入れる (依頼 337 の机の絵と同じ考え方. 依頼 337 の絵は 前の回の むら)."""
    po = P1.Post(json.loads(gain_path(var).read_text())["gain_bgr"])
    cam = po.cams["desk"]
    maps = []
    for f in frames_of(ep):
        k = f["frame"]
        p = OUT / ep / f"blf_{var}_s{S}" / f"{k:03d}_desk.png"
        if not p.exists():
            continue
        real = cv2.imread(str(src_of(ep) / "real" / f"{k:03d}_desk.png")).astype(np.float32).mean(2)
        sim = cv2.imread(str(p)).astype(np.float32).mean(2)
        lab, _ = P3.lab363(po, ep, k, "desk")
        red = MS.red_mask(cv2.imread(str(src_of(ep) / "real" / f"{k:03d}_desk.png")))
        red = np.zeros(lab.shape, bool) if red is None else red
        box = np.isin(lab, BOX)
        T = (lab == L_TABLE) & po.maps["desk"].good & ~P3.di(np.isin(lab, ARM + (L_BLOCK,)) | red, 25) & ~P3.di(box | shifted(box, REAL_BOX_SHIFT), 80)
        w = cv2.GaussianBlur(T.astype(np.float32), (0, 0), sigma_px)
        rs = cv2.GaussianBlur(real * T, (0, 0), sigma_px) / np.maximum(w, 1e-3)
        ss = cv2.GaussianBlur(sim * T, (0, 0), sigma_px) / np.maximum(w, 1e-3)
        m = np.where(w > 0.2, rs / np.maximum(ss, 1), np.nan)
        maps.append(m)
    R = np.nanmedian(np.stack(maps), 0)
    R = R / np.nanmedian(R)
    ok = ~np.isnan(R)
    # 抜けた所 (箱のまわり・絵の外) も含めて 1 つのなめらかな面にする (σ 50px の重み付きならし. 埋めた所の縁が出ないように)
    wt = cv2.GaussianBlur(ok.astype(np.float32), (0, 0), 50)
    Rf = cv2.GaussianBlur(np.where(ok, R, 0).astype(np.float32), (0, 0), 50) / np.maximum(wt, 1e-3)
    R = np.where(wt > 0.02, Rf, 1.0).astype(np.float32)
    R = np.clip(R, 0.8, 1.25)
    # 机の面へ (appearance_337.table_textures と同じ写し方)
    tx, ty = (0, 600), (-350, 350)
    xs = np.arange(tx[0], tx[1]) + 0.5
    ys = ty[1] - np.arange(ty[1] - ty[0]) - 0.5
    X, Y = np.meshgrid(xs, ys)
    import sim_330 as S330
    px = S330.project_arm(np.c_[X.ravel(), Y.ravel(), np.zeros(X.size)], cam).reshape(X.shape + (2,)).astype(np.float32)
    C = cv2.remap(R, px[..., 0], px[..., 1], cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
    tex = cv2.imread(str(OUT / "_tex" / base)).astype(np.float32)
    out = OUT / "_tex" / f"table_fit_{var}.png"
    cv2.imwrite(str(out), np.clip(tex * C[..., None] + 0.5, 0, 255).astype(np.uint8))
    cv2.imwrite(str(OUT / "_tex" / f"table_fit_{var}_ratio.png"), np.clip((R - 0.8) / 0.45 * 255, 0, 255).astype(np.uint8))
    print(out, "C range", float(np.percentile(C, 1)), float(np.percentile(C, 99)), "frames", len(maps))


# ---- 倍率・仕上げ -------------------------------------------------------------------------------

def fit_gain(ep, var, frames=None):
    """post_363.fit_gain と同じ (カメラごとに 実機の平均の色 ÷ Blender の平均の色. 2 回)."""
    po = P1.Post()
    src = src_of(ep)
    fr = [f for f in frames_of(ep) if frames is None or f["frame"] in frames]
    g = {"desk": np.ones(3), "wrist": np.ones(3)}
    for _ in range(2):
        po.gain = {k: list(v) for k, v in g.items()}
        for cam in ("desk", "wrist"):
            rs, bs = [], []
            for f in fr:
                k = f["frame"]
                p = OUT / ep / f"bl_{var}_s{S}" / f"{k:03d}_{cam}.png"
                if not p.exists():
                    continue
                lab = cv2.imread(str(src / "lab" / f"{k:03d}_{cam}.png"), 0)
                real = cv2.imread(str(src / "real" / f"{k:03d}_{cam}.png")).astype(np.float64)
                bl = po.finish(po.raw(p, cam), cam, lab).astype(np.float64)
                ok = po.maps[cam].good
                rs.append(real[ok].mean(0))
                bs.append(bl[ok].mean(0))
            if rs:
                g[cam] = g[cam] * np.mean(rs, 0) / np.mean(bs, 0)
    res = {"made_by": "so101/blender/post_364.py --fit-gain (依頼 364)", "episode": ep, "var": var, "samples": S,
           "frames": len(fr), "gain_bgr": {k: [round(float(x), 4) for x in v] for k, v in g.items()},
           "how": "post_361.fit_gain と同じ (カメラごとに 実機の平均の色 ÷ Blender の平均の色). 比べる 3 本と別の本"}
    gain_path(var).write_text(json.dumps(res, ensure_ascii=False, indent=1))
    print(var, res["gain_bgr"], flush=True)


def finish(ep, var):
    po = P1.Post(json.loads(gain_path(var).read_text())["gain_bgr"])
    src = src_of(ep)
    d = OUT / ep / f"blf_{var}_s{S}"
    d.mkdir(parents=True, exist_ok=True)
    for f in frames_of(ep):
        k = f["frame"]
        for cam in ("desk", "wrist"):
            p = OUT / ep / f"bl_{var}_s{S}" / f"{k:03d}_{cam}.png"
            if not p.exists():
                continue
            lab = cv2.imread(str(src / "lab" / f"{k:03d}_{cam}.png"), 0)
            cv2.imwrite(str(d / f"{k:03d}_{cam}.png"), po.finish(po.raw(p, cam), cam, lab))


# ---- 測る -------------------------------------------------------------------------------------

def Lab(img):
    x = cv2.cvtColor(img.astype(np.float32) / 255, cv2.COLOR_BGR2LAB)
    return x[..., 0], x[..., 1]


def closed(L, k=9):
    """細い暗い物 (実機のケーブル・机のしみ) を消す (明るさの閉じ: 広げてから縮める)."""
    se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k, k))
    return cv2.morphologyEx(L, cv2.MORPH_CLOSE, se)


def shifted(m, d):
    return P3.shift(m, d) if m.any() else m


def grid_cells(L, T, nx=8, ny=6):
    H, W = L.shape
    out = np.full((ny, nx), np.nan)
    for j in range(ny):
        for i in range(nx):
            sl = (slice(j * H // ny, (j + 1) * H // ny), slice(i * W // nx, (i + 1) * W // nx))
            m = T[sl]
            if m.mean() >= 0.3:
                out[j, i] = np.median(L[sl][m])
    return out


def edge_profile(L, T, box, side, n=70):
    """箱の外の辺 (side = "down" / "right") から外へ 0〜n px の L の形 (辺に沿って 箱の 30〜100% の所の中央値). 机でない画素は除く."""
    ys, xs = np.nonzero(box)
    y0, y1, x0, x1 = ys.min(), ys.max(), xs.min(), xs.max()
    prof = np.full(n, np.nan)
    for t in range(n):
        if side == "down":
            y = y1 + 1 + t
            if y >= L.shape[0]:
                break
            xx = np.arange(int(x0 + 0.3 * (x1 - x0)), x1 + 1)
            yy = np.full_like(xx, y)
        else:
            x = x1 + 1 + t
            if x >= L.shape[1]:
                break
            yy = np.arange(int(y0 + 0.3 * (y1 - y0)), y1 + 1)
            xx = np.full_like(yy, x)
        ok = T[yy, xx]
        if ok.sum() >= 0.6 * len(ok):
            prof[t] = np.median(L[yy[ok], xx[ok]])
    return prof


def shadow_of_profile(p):
    """影の形: 机 = 外の端 10px の中央値. まず 影の芯 (内の 10% 点) と机の中間を 外から見て最後に下回る所 t_0.5 (影の長さ) を出し,
    影の本体 = 辺から 3px 〜 t_0.5 − 6px の中央値 として, 濃さ = 本体 ÷ 机, ぼけ幅 = 本体 + f × (机 − 本体) を最後に下回る所の
    f = 0.9 と 0.1 の差 (px. 影の外のふち)."""
    v = np.nonzero(~np.isnan(p))[0]
    if len(v) < 25 or v[-1] < 30:
        return np.nan, np.nan, np.nan
    plate = np.nanmedian(p[v[-1] - 9:v[-1] + 1])  # 外の端の 10px (下は 60〜70px, 絵の端に近い右は 手前まで)

    def last_below(core, f):
        th = core + f * (plate - core)
        below = [i for i in v if p[i] < th]
        if not below:
            return 0.0
        t = max(below)
        if t + 1 < len(p) and not np.isnan(p[t + 1]):
            return t + (th - p[t]) / max(1e-6, p[t + 1] - p[t])
        return float(t)
    core = np.nanpercentile(p[:v[-1] - 9], 10)
    if plate - core < 1.0:
        return core / plate, np.nan, np.nan
    t50 = last_below(core, 0.5)
    body = p[3:max(4, int(t50) - 5)]
    body = np.nanmedian(body) if np.isfinite(body).sum() >= 3 else core
    if plate - body < 1.0:
        return body / plate, np.nan, t50
    return body / plate, last_below(body, 0.9) - last_below(body, 0.1), t50


def measure_desk(po, ep, k, img, is_real, lab, rr_all):
    """机側の 1 枚の値."""
    L, A = Lab(img)
    good = po.maps["desk"].good
    box = np.isin(lab, BOX)
    arm = np.isin(lab, ARM)
    blk = lab == L_BLOCK
    if is_real:
        box = shifted(box, REAL_BOX_SHIFT)
    red = MS.red_mask(img)
    red = np.zeros(L.shape, bool) if red is None else red
    tab = ((lab == L_TABLE) | np.isin(lab, BOX)) if is_real else (lab == L_TABLE)  # 机の画素 (実機は ずらした箱を除く)
    T = tab & good & ~P3.di(arm | blk | rr_all, 6) & ~P3.di(box, 3)
    Lc = closed(L)
    r = {"_Lc": Lc, "_T": T}
    ref = float(np.median(L[T]))
    r["table_L"] = ref
    cells = grid_cells(L, T)
    r["grid_std"] = float(np.nanstd(cells))
    r["_cells"] = cells
    near_arm = P3.di(arm, 60).__and__(P3.di(box, 60)).any()
    if not near_arm and box.sum() > 500:
        ys, xs = np.nonzero(box)
        cy, cx = ys.mean(), xs.mean()
        yy, xx = np.mgrid[0:L.shape[0], 0:L.shape[1]]
        panel_side = (yy - cy) + (xx - cx) < 0  # 絵の左上の半分 (パネルの側)
        near = P3.di(box, 40) & ~P3.di(box, 8) & T & panel_side
        far = P3.di(box, 160) & ~P3.di(box, 80) & T
        if near.sum() > 300 and far.sum() > 1000:
            r["halo_dL"] = float(np.median(L[near]) - np.median(L[far]))
        for side in ("down", "right"):
            dep, wid, at = shadow_of_profile(edge_profile(Lc, T, box, side))
            r[f"boxsh_{side}_depth"], r[f"boxsh_{side}_width"], r[f"boxsh_{side}_len"] = dep, wid, at
        inner = np.isin(lab, (L_BOXF, L_BOXW))
        if is_real:
            inner = shifted(inner, REAL_BOX_SHIFT)
        inner = P3.er(inner, 1)
        if inner.sum() > 500:
            ys, xs = np.nonzero(inner)
            y0, y1, x0, x1 = ys.min(), ys.max() + 1, xs.min(), xs.max() + 1
            g = np.full((4, 4), np.nan)
            for j in range(4):
                for i in range(4):
                    sl = (slice(y0 + j * (y1 - y0) // 4, y0 + (j + 1) * (y1 - y0) // 4), slice(x0 + i * (x1 - x0) // 4, x0 + (i + 1) * (x1 - x0) // 4))
                    m = inner[sl]
                    if m.sum() > 20:
                        g[j, i] = np.median(L[sl][m])
            r["_inner"] = g
            r["inner_L"] = float(np.nanmedian(g))
            r["inner_top_minus_bottom"] = float(np.nanmean(g[:2]) - np.nanmean(g[2:]))
    # 腕の影
    if arm.sum() > 3000:
        R = P3.di(arm, 80) & ~P3.di(arm, 5) & T & ~P3.di(box, 50)
        R2 = R & ~P3.di(arm, 8)
        if R.sum() > 3000:
            p5 = float(np.percentile(Lc[R], 5))
            r["armsh_depth"] = p5 / ref
            Ls = cv2.GaussianBlur(Lc, (0, 0), 1.5)
            gx, gy = cv2.Sobel(Ls, cv2.CV_32F, 1, 0, ksize=3) / 8, cv2.Sobel(Ls, cv2.CV_32F, 0, 1, ksize=3) / 8
            gm = np.hypot(gx, gy)
            gmax = float(np.percentile(gm[R2], 98))
            r["armsh_width"] = 1.02 * (ref - p5) / max(gmax, 1e-3) if ref - p5 > 2 else np.nan
    # ブロック
    r.update(block_vals(L, A, red, lab == L_TABLE))
    return r


def block_vals(L, A, red, tm):
    r = {}
    if red.sum() >= 60:
        ring = P3.di(red, 12) & ~P3.di(red, 3) & tm
        if ring.sum() > 100 and tm.sum() > 2000:
            r["ring_a"] = float(np.median(A[ring]) - np.median(A[tm]))
        inner = P3.er(red, 1)
        if inner.sum() >= 40:
            r["blk_p98"] = float(np.percentile(L[inner], 98))
            r["blk_hot"] = float((L[inner] > 70).mean())
            r["blk_p995"] = float(np.percentile(L[inner], 99.5))
    return r


def measure(eps, vars_, tag):
    po = P1.Post()
    rows, cells = [], []
    for ep in eps:
        src = src_of(ep)
        for f in frames_of(ep):
            k = f["frame"]
            ims = {}
            for v in vars_:
                p = sim_path(ep, v, k, "desk")
                if p.exists():
                    ims[v] = {cam: cv2.imread(str(sim_path(ep, v, k, cam))) if sim_path(ep, v, k, cam).exists() else None
                              for cam in ("desk", "wrist")}
            if not ims:
                continue
            ims = {"real": {cam: cv2.imread(str(src / "real" / f"{k:03d}_{cam}.png")) for cam in ("desk", "wrist")}, **ims}
            labd, _ = P3.lab363(po, ep, k, "desk")
            rr = np.zeros(labd.shape, bool)
            for v, im in ims.items():
                m = MS.red_mask(im["desk"])
                if m is not None:
                    rr |= m
            base = {"ep": ep, "frame": k, "stage": f["stage"], "held": f["held"]}
            per = {}
            for v, im in ims.items():
                per[v] = measure_desk(po, ep, k, im["desk"], v == "real", labd, rr)
            # 格子の差・箱の内側の差・影の地図の差 (実機と)
            near = P3.di(np.isin(labd, ARM + BOX), 100)
            for v, r in per.items():
                if v != "real":
                    ok = r["_T"] & per["real"]["_T"] & near
                    if ok.sum() > 3000:
                        dd = cv2.GaussianBlur(r["_Lc"], (0, 0), 2) - cv2.GaussianBlur(per["real"]["_Lc"], (0, 0), 2)
                        dd = dd[ok] - np.median(dd[ok])
                        r["shmap_rms"] = float(np.sqrt(np.mean(dd ** 2)))
                    a, b = r["_cells"], per["real"]["_cells"]
                    ok = ~np.isnan(a) & ~np.isnan(b)
                    r["grid_diff"] = float(np.abs((a[ok] - a[ok].mean()) - (b[ok] - b[ok].mean())).mean()) if ok.sum() > 10 else np.nan
                    if "_inner" in r and "_inner" in per["real"]:
                        a, b = r["_inner"], per["real"]["_inner"]
                        ok = ~np.isnan(a) & ~np.isnan(b)
                        if ok.sum() > 8:
                            r["inner_corr"] = float(np.corrcoef(a[ok], b[ok])[0, 1])
                            r["inner_absdiff"] = float(np.abs(a[ok] - b[ok]).mean())
                cells.append({**base, "img": v, "cells": [None if np.isnan(x) else round(float(x), 2) for x in r["_cells"].ravel()],
                              "inner": [None if np.isnan(x) else round(float(x), 2) for x in r.get("_inner", np.full((4, 4), np.nan)).ravel()]})
            # 手首
            has_w = all(im["wrist"] is not None for im in ims.values())
            labw, nzw = P3.lab363(po, ep, k, "wrist")
            for v, im in (ims.items() if has_w else ()):
                L, A = Lab(im["wrist"])
                red = MS.red_mask(im["wrist"])
                red = np.zeros(L.shape, bool) if red is None else red
                w = block_vals(L, A, red, (labw == L_TABLE) & po.maps["wrist"].good)
                per[v].update({f"w_{q}": x for q, x in w.items()})
            # 面ごとの明るさ (依頼 363 と同じ): ブロックの上の面・横の面
            for cam in (("desk", "wrist") if has_w else ("desk",)):
                R = P3.regions(po, ep, k, cam, ims["real"][cam])
                R.pop("block_shift_px", None)
                for nm in ("block_top", "block_side", "box_floor", "box_inwall"):
                    if nm in R:
                        mr, ms = R[nm]
                        for v, im in ims.items():
                            m = mr if v == "real" else ms
                            per[v][f"{cam[0]}_{nm}"] = float(np.median(Lab(im[cam])[0][m]))
            for v, r in per.items():
                rows.append({**base, "img": v, **{q: (round(x, 4) if isinstance(x, float) else x) for q, x in r.items() if not q.startswith("_")}})
        print(ep, "done", flush=True)
    OUT.mkdir(exist_ok=True)
    pd.DataFrame(rows).to_csv(OUT / f"m_{tag}.csv", index=False)
    (OUT / f"m_{tag}_cells.json").write_text(json.dumps(cells))
    print("→", OUT / f"m_{tag}.csv")


COLS = ["table_L", "grid_std", "grid_diff", "halo_dL", "shmap_rms", "boxsh_down_depth", "boxsh_down_len", "boxsh_down_width", "boxsh_right_depth", "boxsh_right_len", "boxsh_right_width",
        "armsh_depth", "armsh_width", "inner_L", "inner_top_minus_bottom", "inner_corr", "inner_absdiff",
        "ring_a", "blk_p98", "blk_p995", "blk_hot", "w_ring_a", "w_blk_p98", "w_blk_p995", "w_blk_hot", "d_block_top", "d_block_side", "w_block_top", "w_block_side",
        "d_box_floor", "d_box_inwall", "w_box_floor", "w_box_inwall"]


def summ(tag, stages=None):
    d = pd.read_csv(OUT / f"m_{tag}.csv")
    if stages:
        d = d[d.stage.isin(stages)]
    cols = [c for c in COLS if c in d.columns]
    t = d.groupby("img", sort=False)[cols].median().T
    n = d.groupby("img", sort=False)[cols].count().T.iloc[:, 0].rename("n")
    out = pd.concat([t, n], axis=1)
    with pd.option_context("display.width", 250, "display.max_columns", 30, "display.float_format", "{:.3f}".format):
        print(out)
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--make-tex", type=int, default=0)
    ap.add_argument("--make-tex-fit", default="", help="<本>:<組> (平らにした机の絵 × 実機との大きなむらの比)")
    ap.add_argument("--fit-gain", default="")
    ap.add_argument("--finish", default="")
    ap.add_argument("--measure", default="")
    ap.add_argument("--summ", default="")
    ap.add_argument("--var", default="")
    ap.add_argument("--vars", default="")
    ap.add_argument("--frames", default="")
    ap.add_argument("--tag", default="")
    a = ap.parse_args()
    if a.make_tex:
        make_tex(a.make_tex)
    if a.make_tex_fit:
        ep, var = a.make_tex_fit.split(":")
        make_tex_fit(ep, var)
    for var in [v for v in a.var.split(",") if v]:
        if a.fit_gain:
            fit_gain(a.fit_gain, var, {int(x) for x in a.frames.split(",")} if a.frames else None)
        if a.finish:
            for ep in a.finish.split(","):
                finish(ep, var)
    if a.measure:
        measure(a.measure.split(","), a.vars.split(","), a.tag or "x")
    if a.summ:
        summ(a.summ)


if __name__ == "__main__":
    main()
