"""依頼 367: MuJoCo の絵 (と実機の絵) で 箱の影・腕の影・影の地図の差を測る. 測り方は 依頼 364 (so101/blender/post_364.py) と同じ.
post_364 の edge_profile・shadow_of_profile・closed・Lab をここに写した (so101/blender/ は読まない. 依頼 368 が使っているため).

違うところ:
- ラベルは MuJoCo の seg_labels (appearance_337 の L_*). 箱 = 底 + 壁. 腕 = 腕・サーボ・爪
- 箱は box_365.json (実機の机側の絵の上の切り口に当てた位置) なので 実機に当てる箱のマスクを ずらさない (依頼 364 は 古い箱の位置のため (−7, −11)px ずらした)
- 絵のうちで使える所 (歪みの外を除く) は シムの絵が真っ黒でない所

  measure_desk(img, lab, ref=None)  → 箱の影 下・右 (濃さ・長さ・ぼけ幅), 腕の影 (濃さ・ぼけ幅の目安), 机の L, 箱の内側の L
  shadow_map_diff(real, sim, lab)   → 影の地図の差 (腕・箱から 100px 以内の机で L の差 − 中央値 の 二乗平均の根)
"""

import sys
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import appearance_337 as A7  # noqa: E402
import measure_scene_330 as MS  # noqa: E402

BOX = (A7.L_BOXF, A7.L_BOXW)
ARM = (A7.L_ARM, A7.L_SERVO, A7.L_JAW)


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


def di(m, px):
    return A7.dilate(m, px) if m.any() else m


def er(m, px):
    return A7.erode(m, px) if m.any() else m


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


def edge_profile(L, T, box, side, n=70):
    """post_364.edge_profile と同じ: 箱の外の辺 (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):
    """post_364.shadow_of_profile と同じ: (濃さ, ぼけ幅 px, 長さ 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])

    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 table_mask(img, lab, good):
    red = MS.red_mask(img)
    red = np.zeros(lab.shape, bool) if red is None else red
    arm, blk, box = np.isin(lab, ARM), lab == A7.L_BLOCK, np.isin(lab, BOX)
    return (lab == A7.L_TABLE) & good & ~di(arm | blk | red, 6) & ~di(box, 3)


def measure_desk(img, lab, good, red_all=None):
    """机側の 1 枚 (post_364.measure_desk の 箱の影・腕の影・箱の内側 の所)."""
    L, _ = Lab(img)
    box, arm = np.isin(lab, BOX), np.isin(lab, ARM)
    T = table_mask(img, lab, good)
    if red_all is not None:
        T &= ~di(red_all, 6)
    Lc = closed(L)
    r = {"table_L": float(np.median(L[T])) if T.sum() > 100 else np.nan}
    ref = r["table_L"]
    near_arm = (di(arm, 60) & di(box, 60)).any()
    r["box_clear"] = int(not near_arm)
    if not near_arm and box.sum() > 500:
        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 = er(box, 1)
        if inner.sum() > 500:
            r["inner_L"] = float(np.median(L[inner]))
            fl = er(lab == A7.L_BOXF, 1)
            if fl.sum() > 200:
                ys = np.nonzero(fl)[0]
                mid = np.median(ys)
                r["floor_top_minus_bottom"] = float(np.median(L[fl & (np.arange(L.shape[0])[:, None] < mid)]) -
                                                    np.median(L[fl & (np.arange(L.shape[0])[:, None] >= mid)]))
    if arm.sum() > 3000:
        R = di(arm, 80) & ~di(arm, 5) & T & ~di(box, 50)
        R2 = R & ~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
            gmax = float(np.percentile(np.hypot(gx, gy)[R2], 98))
            r["armsh_width"] = 1.02 * (ref - p5) / max(gmax, 1e-3) if ref - p5 > 2 else np.nan
    return r


def shadow_map_diff(real, sim, lab, good):
    """post_364 の 影の地図の差: 腕・箱から 100px 以内の机 (両方の机の画素) で σ 2px にならした L の差 − 中央値 の 二乗平均の根."""
    Lr, _ = Lab(real)
    Ls, _ = Lab(sim)
    T = table_mask(real, lab, good) & table_mask(sim, lab, good)
    near = di(np.isin(lab, ARM + BOX), 100) & T
    if near.sum() < 2000:
        return np.nan
    d = cv2.GaussianBlur(closed(Ls), (0, 0), 2) - cv2.GaussianBlur(closed(Lr), (0, 0), 2)
    x = d[near] - np.median(d[near])
    return float(np.sqrt(np.mean(x ** 2)))


def good_of(sim):
    return sim.max(2) > 8
