"""依頼 389 の 2: 手首の絵で 板の縁の向こう (部屋) に貼る 遠くの背景の絵 (世界の背景. 正距円筒 2048×1024) を作る.

(i)  room_i.png: 実機の HOME の手首の絵 (成功 50 本のうち 比べる 3 本 (割り振り 0・5・3) を除いた 47 本の 10 コマ目. 腕は止まっていて 人は写っていない) の
     板の縁より上 (当てはめた板 (edge_389.json) に光線が当たらず, fill_388.room_mask でも縁より上の所. 縁から 6px は離す. 5 本以上に写った向きだけ) の画素を, その本・そのコマの手首カメラの 4×4 (check_372/poses. Blender で描く位置と同じ) で
     向きに直して 正距円筒に並べ, 47 本の中央値をとる. 写っていない向きは 近い所の色を広げて埋める.
(ii) room_ii.png: 同じ画素を 明るい所 (白い壁・板) と 暗い所 (床・家具) の 2 つに分け (L の大津の閾値), 色はそれぞれの中央値.
     形は 「ある向きの帯 (方位 φa〜φb) は明るい壁・ほかは暗い床」 だけ (帯の端は 明るい所の割合が 1/2 になる方位).

色: 描いた絵は 仕上げ (post_361.Post) で 倍率 (look の post.gain_bgr × appearance の camera_gain) と 手首の周辺減光を掛けられるので,
実機の画素をそれで割った値を 背景の明るさ (Raw. 0〜1) にする. 絵は 16bit・Non-Color で読む.
向きの決まり (Blender の正距円筒): u = 0.5 − atan2(y, x) / 2π, v = 0.5 + 仰角 / π (v は下から). 書く PNG は上の行が v = 1.

使い方 (conda の lerobot 環境で): python so101/sim/look_389/room_389.py   → look_389/room/room_i.png・room_ii.png・room_389.json・figs/room_389.png
"""
import json
import math
import sys
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent.parent
L388 = HERE.parent / "look_388"
sys.path.insert(0, str(L388))
sys.path.insert(0, str(SO101 / "blender"))
sys.path.insert(0, str(SO101 / "sim"))
import proj_388 as PJ  # noqa: E402
import fill_388 as FL  # noqa: E402
import post_361 as P1  # noqa: E402
sys.path.insert(0, str(HERE))
import edge_389 as ED  # noqa: E402
import simreplay_334 as R  # noqa: E402

LOOK = json.loads((SO101 / "blender" / "look_blender_v2.json").read_text())
DS = "so101_redblock_box_ideal_var_v2"
TEST = (0, 3, 5)
K_HOME = 10
EW, EH = 2048, 1024
MARGIN = 6
BOARD = json.loads((HERE / "edge_389.json").read_text())["board"]


def real_frame(src_ep, k):
    for kk, im in R.iter_frames(DS, src_ep, "wrist"):
        if kk == k:
            return im
    raise RuntimeError(f"ep{src_ep} {k}")


def env_dirs():
    """正距円筒の画素 (上の行から) → 世界の向き (単位)."""
    u = (np.arange(EW) + 0.5) / EW
    v = 1 - (np.arange(EH) + 0.5) / EH
    az = (0.5 - u) * 2 * math.pi  # atan2(y, x)
    el = (v - 0.5) * math.pi
    A, E = np.meshgrid(az, el)
    return np.stack([np.cos(E) * np.cos(A), np.cos(E) * np.sin(A), np.sin(E)], -1)


def sample(M, img, valid, D):
    """世界の向き D (H×W×3) を カメラ M (Blender の 4×4) の 640×480 (歪みあり) に写し, valid の所の色を取る."""
    Rm, _ = PJ.to_cv(M)
    dc = D.reshape(-1, 3) @ Rm.T
    front = dc[:, 2] > 0.05
    x = dc[front, :2] / dc[front, 2:3]
    inside = (np.abs(x[:, 0]) < 1.6) & (np.abs(x[:, 1]) < 1.3)  # 歪みの式が折り返さない範囲
    idx = np.where(front)[0][inside]
    pts = np.c_[x[inside], np.ones(inside.sum())]
    uv, _ = cv2.projectPoints(pts.reshape(-1, 1, 3), np.zeros(3), np.zeros(3), PJ.CAMS["wrist"]["K"], PJ.CAMS["wrist"]["D"])
    uv = uv.reshape(-1, 2)
    h, w = valid.shape
    ok = (uv[:, 0] >= 0) & (uv[:, 0] < w - 1) & (uv[:, 1] >= 0) & (uv[:, 1] < h - 1)
    # 歪みの往復で同じ向きに戻る所だけ (端の折り返しを除く)
    back = cv2.undistortPointsIter(uv[ok].reshape(-1, 1, 2), PJ.CAMS["wrist"]["K"], PJ.CAMS["wrist"]["D"], None, None,
                                   (cv2.TERM_CRITERIA_COUNT | cv2.TERM_CRITERIA_EPS, 100, 1e-10)).reshape(-1, 2)
    good = np.zeros(len(uv), bool)
    good[np.where(ok)[0]] = np.hypot(*(back - pts[ok, :2]).T) < 1e-3
    idx, uv = idx[good], uv[good]
    vi = valid[np.rint(uv[:, 1]).astype(int), np.rint(uv[:, 0]).astype(int)]
    idx, uv = idx[vi], uv[vi]
    x0, y0 = np.floor(uv[:, 0]).astype(int), np.floor(uv[:, 1]).astype(int)
    fx, fy = (uv[:, 0] - x0)[:, None], (uv[:, 1] - y0)[:, None]
    col = ((1 - fx) * (1 - fy) * img[y0, x0] + fx * (1 - fy) * img[y0, x0 + 1]
           + (1 - fx) * fy * img[y0 + 1, x0] + fx * fy * img[y0 + 1, x0 + 1])
    return idx, col, uv


def fill_holes(img, have):
    """写っていない所を 近い所の色で埋める (押し引き: 縮めた絵の平均を広げる)."""
    lv = [(img * have[..., None], have.astype(np.float32))]
    while min(lv[-1][1].shape) > 4:
        c, w = lv[-1]
        lv.append((cv2.resize(c, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA), cv2.resize(w, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)))
    c, w = lv[-1]
    out = c / np.maximum(w[..., None], 1e-6)
    for c, w in reversed(lv[:-1]):
        up = cv2.resize(out, (w.shape[1], w.shape[0]), interpolation=cv2.INTER_LINEAR)
        cur = c / np.maximum(w[..., None], 1e-6)
        a = np.clip(w, 0, 1)[..., None]
        out = a * cur + (1 - a) * up
    return out


def main():
    po = P1.Post(LOOK["post"]["gain_bgr"])
    G = po.look.gain("wrist") * np.array(LOOK["post"]["gain_bgr"]["wrist"], np.float32)  # BGR
    vig = po.look.vignette(PJ.CAMS["wrist"]["K"])[..., 0]
    D = env_dirs()
    stacks, used = [], []
    allcols = []
    for i in range(50):
        if i in TEST:
            continue
        P = json.loads((SO101 / "check_372" / "poses" / f"ep{i:02d}" / "poses.json").read_text())
        f = [x for x in P["frames"] if x["frame"] == K_HOME][0]
        if f["stage"] != "HOME":
            continue
        real = real_frame(P["source_episode"], K_HOME)
        rm = ED.room_pixels(f["cams"]["wrist"], BOARD) & FL.room_mask(real)  # 板 (当てはめた縁) に当たらず 実機でも縁より上
        valid = cv2.erode(rm.astype(np.uint8), np.ones((2 * MARGIN + 1, 1), np.uint8)).astype(bool) & po.maps["wrist"].good
        lin = real.astype(np.float32) / 255.0 / (G[None, None, :] * vig[..., None])  # 仕上げを外した明るさ (BGR)
        idx, col, uv = sample(f["cams"]["wrist"], lin, valid, D)
        e = np.full((EH * EW, 3), np.nan, np.float32)
        e[idx] = col
        stacks.append(e)
        used.append({"plan_index": i, "source_episode": P["source_episode"], "pixels": int(len(idx))})
        allcols.append(real[valid])
        print(i, P["source_episode"], len(idx), flush=True)
    S_ = np.stack(stacks)
    have = np.isfinite(S_[..., 0]).sum(0) >= 5
    med = np.nanmedian(np.where(np.isfinite(S_), S_, np.nan), axis=0)
    med = np.where(have[:, None], med, 0).reshape(EH, EW, 3)
    have = have.reshape(EH, EW)
    env_i = fill_holes(med.astype(np.float32), have)
    (HERE / "room").mkdir(exist_ok=True)

    def save(name, bgr):
        cv2.imwrite(str(HERE / "room" / name), np.clip(bgr * 65535, 0, 65535).astype(np.uint16))  # cv2 は BGR で書く → PNG は RGB

    save("room_i.png", env_i)
    # (ii) 明るい壁と暗い床の 2 色
    lab = cv2.cvtColor(np.clip(med * 255 * G, 0, 255).astype(np.uint8), cv2.COLOR_BGR2LAB)[..., 0]
    thr, _ = cv2.threshold(lab[have].reshape(-1, 1), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    bright = (lab > thr) & have
    frac = bright.sum(0) / np.maximum(have.sum(0), 1)
    cols = np.where(have.sum(0) > 20)[0]
    inb = cols[frac[cols] > 0.5]
    # いちばん長い 続いた帯
    runs, s0 = [], inb[0]
    for a, b in zip(inb[:-1], inb[1:]):
        if b != a + 1:
            runs.append((s0, a))
            s0 = b
    runs.append((s0, inb[-1]))
    ua, ub = max(runs, key=lambda r: r[1] - r[0])
    c_wall = np.median(med[bright], axis=0)
    c_floor = np.median(med[have & ~bright], axis=0)
    env_ii = np.empty_like(env_i)
    env_ii[:] = c_floor
    env_ii[:, ua:ub + 1] = c_wall
    save("room_ii.png", env_ii)
    az = lambda u: math.degrees((0.5 - (u + 0.5) / EW) * 2 * math.pi)  # noqa: E731
    out = {"made_by": "so101/sim/look_389/room_389.py (依頼 389)",
           "from": f"{DS} の成功 50 本 (check_372/poses の割り振り) のうち 0・3・5 を除いた本の {K_HOME} コマ目の手首の絵", "used": used,
           "env_size": [EW, EH], "covered_frac": round(float(have.mean()), 4),
           "covered_az_deg": [round(az(int(np.where(have.any(0))[0].max())), 1), round(az(int(np.where(have.any(0))[0].min())), 1)],
           "covered_el_deg": [round(90 - 180 * (int(np.where(have.any(1))[0].max()) + 0.5) / EH, 1), round(90 - 180 * (int(np.where(have.any(1))[0].min()) + 0.5) / EH, 1)],
           "gain_bgr_total_wrist": [round(float(x), 4) for x in G],
           "ii": {"otsu_L": float(thr), "wall_az_deg": [round(az(int(ub)), 1), round(az(int(ua)), 1)],
                  "wall_rgb_lin": [round(float(x), 4) for x in c_wall[::-1]], "floor_rgb_lin": [round(float(x), 4) for x in c_floor[::-1]],
                  "wall_bgr_8bit_after_post": [round(float(x), 1) for x in c_wall * 255 * G], "floor_bgr_8bit_after_post": [round(float(x), 1) for x in c_floor * 255 * G]}}
    (HERE / "room" / "room_389.json").write_text(json.dumps(out, ensure_ascii=False, indent=1))
    print(json.dumps({k: v for k, v in out.items() if k != "used"}, ensure_ascii=False))
    (HERE / "figs").mkdir(exist_ok=True)
    sh = lambda e: np.clip(e * 255 * G, 0, 255).astype(np.uint8)  # noqa: E731
    ys, xs = np.where(have)
    y0, y1, x0, x1 = max(0, ys.min() - 60), min(EH, ys.max() + 60), max(0, xs.min() - 60), min(EW, xs.max() + 60)
    vis = np.vstack([sh(env_i)[y0:y1, x0:x1], sh(env_ii)[y0:y1, x0:x1]])
    cv2.imwrite(str(HERE / "figs" / "room_389.png"), vis)


if __name__ == "__main__":
    main()
