"""依頼 389 の 1: 実機の HOME の手首の絵 (check_361/ep{NN}/real の 0・5・10・15 コマ. 腕が止まっている所) に写る 白い板の縁 (左に丸い角) を読み,
机の面の高さ (Blender の table_tex の面 z = −2.35mm) へ写して 板の 奥の縁・左の縁・丸い角 を当てはめる.

読み方: 列ごとに 下から見て 明るさ L が 45 未満の画素が 3 つ続く いちばん下の所 (fill_388.room_mask と同じ) を縁とし,
その画素を 同じコマの手首カメラ (look_388/poses/base の 4×4. Blender で描くときと同じ) で 机の面へ写す.
当てはめ: 角を丸めた長方形の 奥の縁 x = x_far・左の縁 y = y_left・角の半径 r・z まわりの向き θ (点から縁までの距離の 2 乗の和を小さくする).
机側のカメラの絵が 全部 板の上か (縁を詰めても 机側に部屋が写らないか) も確かめる.

使い方 (conda の lerobot 環境で): python so101/sim/look_389/edge_389.py   → look_389/edge_389.json・figs/edge_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"))
import proj_388 as PJ  # noqa: E402
import fill_388 as FL  # noqa: E402
import post_361 as P1  # noqa: E402

EPS = ("ep00", "ep05", "ep03")
KS = (0, 5, 10, 15)
Z_TABLE = -0.00235  # table_tex の面 (check_361/scene/geoms.json の 4×4)
COL_STEP = 4


def poses(ep):
    return {f["frame"]: f for f in json.loads((L388 / "poses" / "base" / ep / "poses.json").read_text())["frames"]}


def edge_rows(real):
    m = FL.room_mask(real)
    return np.array([np.where(m[:, x])[0].max() if m[:, x].any() else -1 for x in range(real.shape[1])])


def read_points():
    pts, rec = [], []
    for ep in EPS:
        P = poses(ep)
        for k in KS:
            real = cv2.imread(str(SO101 / "check_361" / ep / "real" / f"{k:03d}_wrist.png"))
            e = edge_rows(real)
            xs = np.arange(0, real.shape[1], COL_STEP)
            # ブロックが縁の手前に写る列 (縁の行が隣とかけ離れる所) は除く
            ok = e[xs] >= 0
            med = cv2.medianBlur(np.clip(e, 0, None).astype(np.uint8), 31).astype(int) if e.max() < 256 else e
            ok &= np.abs(e[xs] - med[xs]) < 6
            W = PJ.back_project_z(P[k]["cams"]["wrist"], np.c_[xs[ok], e[xs[ok]] + 0.5], Z_TABLE, "wrist")
            pts.append(W[:, :2])
            rec.append({"ep": ep, "frame": k, "cols": int(ok.sum())})
    return np.vstack(pts), rec


def dist_rounded(p, x_far, y_left, r, th):
    """板の座標 (θ だけ回した) で 奥・左の角を丸めた 2 本の縁 (手前・右は遠くへ伸びる) への 符号なしの距離."""
    c, s = math.cos(th), math.sin(th)
    u = c * p[:, 0] + s * p[:, 1]
    v = -s * p[:, 0] + c * p[:, 1]
    cu, cv_ = x_far - r, y_left - r
    corner = (u > cu) & (v > cv_)
    d = np.minimum(np.abs(u - x_far), np.abs(v - y_left))  # 内側: 近い方の縁
    d = np.where((u > cu) & (v <= cv_), np.abs(u - x_far), d)  # 奥の縁の帯
    d = np.where((u <= cu) & (v > cv_), np.abs(v - y_left), d)  # 左の縁の帯
    d = np.where(corner, np.abs(np.hypot(u - cu, v - cv_) - r), d)  # 丸い角
    return d


def in_board(xy, b):
    """机の面の点 (m) が 板の上か (edge_389.json の board. 手前・右は限りなし)."""
    th = math.radians(b["yaw_deg"])
    xf, yl, r = b["x_far_mm"] / 1000, b["y_left_mm"] / 1000, b["corner_r_mm"] / 1000
    u = math.cos(th) * xy[:, 0] + math.sin(th) * xy[:, 1]
    v = -math.sin(th) * xy[:, 0] + math.cos(th) * xy[:, 1]
    ok = (u <= xf) & (v <= yl)
    cor = (u > xf - r) & (v > yl - r)
    return ok & ~(cor & (np.hypot(u - (xf - r), v - (yl - r)) > r))


def room_pixels(M, b, shape=(480, 640)):
    """手首カメラ M (Blender の 4×4) の 640×480 の画素のうち 光線が板に当たらない所 (= 部屋)."""
    h, w = shape
    yy, xx = np.mgrid[0:h, 0:w]
    uv = np.c_[xx.ravel(), yy.ravel()].astype(float) + 0.5
    n = cv2.undistortPointsIter(uv.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)
    R, t = PJ.to_cv(M)
    o = -R.T @ t
    d = (R.T @ np.c_[n, np.ones(len(n))].T).T
    s = (Z_TABLE - o[2]) / d[:, 2]
    hit = s > 0
    xy = o[:2] + s[:, None] * d[:, :2]
    room = ~hit
    room[hit] = ~in_board(xy[hit], b)
    return room.reshape(h, w)


def cost(pts, q):
    d = dist_rounded(pts, *q)
    k = 0.005
    return float(np.sum(k * k * (np.sqrt(1 + (d / k) ** 2) - 1)))  # soft_l1 (5mm)


def fit(pts, q0, steps, fixed=()):
    """座標ごとに 刻みを細かくしながら探す (scipy は lerobot の環境に無い)."""
    q = np.array(q0, float)
    st = np.array(steps, float)
    for _ in range(12):
        for _ in range(20):
            moved = False
            for i in range(len(q)):
                if i in fixed:
                    continue
                for sg in (-1, 1):
                    t = q.copy()
                    t[i] = max(0.0, t[i] + sg * st[i]) if i == 2 else t[i] + sg * st[i]
                    if cost(pts, t) < cost(pts, q):
                        q, moved = t, True
            if not moved:
                break
        st /= 2
    return q, dist_rounded(pts, *q)


def desk_footprint(po):
    """机側カメラの 歪みを足した絵の 使える所 (Post の good) の 縁の画素を 机の面へ写した点 (HOME 0 コマ・机側の 4×4)."""
    M = poses("ep00")[0]["cams"]["desk"]
    good = po.maps["desk"].good.astype(np.uint8)
    cs, _ = cv2.findContours(good, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    c = max(cs, key=len).reshape(-1, 2)[::5]
    return PJ.back_project_z(M, c.astype(float) + 0.5, Z_TABLE, "desk")[:, :2]


def main():
    pts, rec = read_points()
    q, res = fit(pts, [0.64, 0.40, 0.05, 0.0], [0.01, 0.01, 0.01, 0.01])
    x_far, y_left, r, th = q
    q0, res0 = fit(pts, [0.64, 0.40, 0.0, 0.0], [0.01, 0.01, 0.0, 0.01], fixed=(2,))
    po = P1.Post()
    fp = desk_footprint(po)
    c, s = math.cos(th), math.sin(th)
    u = c * fp[:, 0] + s * fp[:, 1]
    v = -s * fp[:, 0] + c * fp[:, 1]
    out = {
        "made_by": "so101/sim/look_389/edge_389.py (依頼 389)",
        "how": "実機の HOME の手首の絵 (check_361 ep00・ep05・ep03 の 0・5・10・15 コマ) の板の縁を 列ごとに読み (fill_388.room_mask と同じ: 下から L<45 が 3 つ続く所), "
               "同じコマの手首カメラの 4×4 (look_388/poses/base) と camera_wrist.json の K・歪みで 机の面 z=−2.35mm へ写し, 奥・左の角を丸めた縁を当てはめた",
        "points": int(len(pts)), "frames": rec,
        "board": {"x_far_mm": round(x_far * 1000, 1), "y_left_mm": round(y_left * 1000, 1), "corner_r_mm": round(r * 1000, 1),
                  "yaw_deg": round(math.degrees(th), 2),
                  "units": "アームの座標 (原点 = 台座の回る軸の机の面, +x 前, +y 左). yaw = 板の縁の +x から +y への回り"},
        "residual_mm": {"median": round(float(np.median(res)) * 1000, 2), "p90": round(float(np.percentile(res, 90)) * 1000, 2)},
        "no_corner": {"x_far_mm": round(q0[0] * 1000, 1), "y_left_mm": round(q0[1] * 1000, 1), "yaw_deg": round(math.degrees(q0[3]), 2),
                      "residual_median_mm": round(float(np.median(res0)) * 1000, 2)},
        "desk_cam_footprint_mm": {"x_max": round(float(fp[:, 0].max()) * 1000, 1), "y_max": round(float(fp[:, 1].max()) * 1000, 1),
                                  "x_min": round(float(fp[:, 0].min()) * 1000, 1), "y_min": round(float(fp[:, 1].min()) * 1000, 1),
                                  "inside_board": bool((u < x_far - 0.002).all() and (v < y_left - 0.002).all())},
        "before": {"table_outside": "check_361/scene/geoms.json の table (2m × 2m の箱. 中心 x 338.8mm → x −661〜1339mm・y ±1000mm)",
                   "table_tex": "x 38.8〜638.8mm・y ±350mm"},
        "not_read": "手前の縁 (台座の後ろ) と 右の縁 (y の負の側) は どのコマの手首・机側の絵にも写らないので 読めない. 元のまま (2m の板) にした",
    }
    (HERE / "edge_389.json").write_text(json.dumps(out, ensure_ascii=False, indent=1))
    print(json.dumps({k: out[k] for k in ("board", "residual_mm", "no_corner", "desk_cam_footprint_mm")}, ensure_ascii=False))
    # 絵: 実機 ep00 10 の上に 当てはめた縁を写す
    (HERE / "figs").mkdir(exist_ok=True)
    rows = []
    for ep in EPS:
        real = cv2.imread(str(SO101 / "check_361" / ep / "real" / "010_wrist.png"))
        M = poses(ep)[10]["cams"]["wrist"]
        ang = np.linspace(0, math.pi / 2, 30)
        cu, cv_ = x_far - r, y_left - r
        loc = np.r_[np.c_[np.full(40, x_far), np.linspace(-0.4, cv_, 40)], np.c_[cu + r * np.cos(ang), cv_ + r * np.sin(ang)],
                    np.c_[np.linspace(cu, 0.1, 40), np.full(40, y_left)]]
        Wd = np.c_[c * loc[:, 0] - s * loc[:, 1], s * loc[:, 0] + c * loc[:, 1], np.full(len(loc), Z_TABLE)]
        uv, z = PJ.project(M, Wd, "wrist")
        o = real.copy()
        for (a, b), zz in zip(uv, z):
            if zz > 0 and 0 <= a < 640 and 0 <= b < 480:
                cv2.circle(o, (int(a), int(b)), 2, (0, 255, 0), -1)
        rows.append(o)
    cv2.imwrite(str(HERE / "figs" / "edge_389.png"), cv2.resize(np.hstack(rows), None, fx=0.5, fy=0.5))


if __name__ == "__main__":
    main()
