"""依頼 362: 新しい 50 本 (so101_redblock_box_ideal_var_v2 の成功. 依頼 359 と同じ選び方) を録った回の 見た目の値 (回 v2) を測る
→ sim/appearance_362.json (新しいファイル. appearance_353.json・appearance_355.json は書き換えない). 録ったお手本は読むだけ.

  --bg   机側の背景と机の絵:
           50 本の机側のコマ (BG_STEP コマおき) を重ね, 画素ごとの中央値を 2 回 (依頼 337 appearance_337.background と同じ考え方.
           1 回目の中央値の DARK_REJECT 倍より暗い・(2 − DARK_REJECT) 倍より明るいコマ (腕・影・サーボ) を外して 2 回目).
           外す所: 赤 (ブロック. 6px 広げる), 箱 (80×80×45mm の 8 隅の凸包. 6px 広げる). 残ったコマが HOLE_MIN_N より少ない所は穴 (埋める)
           → check_362/bg_v2.png・bg_v2_hole.png, 机の面の絵 table_texture_v2.png・_mask.png (appearance_337.table_textures と同じ写し方)
           光の倍率 = 背景の灰色の中央値 ÷ 193 (依頼 337 の pos23・pos45 の値. pos1b の 0.834 = 161 ÷ 193 と同じ決め方)
  --gain カメラの倍率: simreplay_362.py の ep*_frames.csv の 机 (table) の 実機 ÷ シム (B・G・R. コマの中央値) を 今の値に掛ける (依頼 353 cal_353 と同じ)
           初めの値: 机側 = pos1b の値, 手首 = v1 の値 ÷ 光の倍率 (手首は自動露出で 机の明るさが回で変わらない. 依頼 337・353)

使い方 (conda の lerobot 環境で):
    python so101/sim/appearance_362.py --bg
    python so101/sim/appearance_362.py --gain --tag cal1          # check_362/cal1/ の比を掛けて appearance_362.json に書く
"""

import argparse
import json
import sys
from datetime import datetime
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import sim_330 as S  # noqa: E402
import simreplay_334 as R  # noqa: E402
import simreplay_359 as Z  # noqa: E402
import simreplay_362 as Y2  # noqa: E402
import measure_scene_330 as MS  # noqa: E402
import appearance_337 as A7  # noqa: E402
import appearance_353 as A3  # noqa: E402

OUT = Y2.OUT
P362 = Y2.PARAMS362
BG_STEP = 12
DARK_REJECT = 0.85
HOLE_MIN_N = 8
REF_GRAY = 193.0  # 依頼 337 summary_337.json desk_brightness の pos23・pos45 の灰色の中央値


def load():
    return json.loads(P362.read_text()) if P362.exists() else {}


def save(p):
    p["request"] = "依頼 362"
    p["how_to_read"] = ("appearance_353.json の 回 (session) の値に 回 v2 (新しい 50 本 so101_redblock_box_ideal_var_v2 を録った回) を足す. "
                        "simreplay_362.py --look v2 が 読んだ中に足して使う (appearance_353.json・appearance_355.json は書き換えない). "
                        "level 8 の残りの見た目 (光の向き・爪・箱・モヤなど) は appearance_355.json のまま")
    P362.write_text(json.dumps(p, ensure_ascii=False, indent=1) + "\n")


def box_mask(cams, box):
    c8 = S.box_corners(box["xy"], box["yaw"], box["size_xy"], 0.0, box["height"])
    px = S.project_arm(c8, cams["desk"]).astype(np.float32)
    hull = cv2.convexHull(px.reshape(-1, 1, 2)).astype(np.int32)
    m = np.zeros((S.H, S.W), np.uint8)
    cv2.fillConvexPoly(m, hull, 1)
    return A7.dilate(m > 0, 6)


def bg_mode():
    cams = S.load_cameras()
    box = Y2.load_box("80")
    bm = box_mask(cams, box)
    eps = Z.pick_episodes()
    stack, excl = [], []
    for e in eps:
        for k, img in R.iter_frames(Z.DS, e["episode_index"], "desk"):
            if k % BG_STEP:
                continue
            stack.append(img)
            excl.append(np.packbits(bm | Y2.red_wide(img), axis=1))
    N = len(stack)
    bg = np.zeros((S.H, S.W, 3), np.float32)
    cnt = np.zeros((S.H, S.W), np.int32)
    for y0 in range(0, S.H, 20):
        y1 = min(S.H, y0 + 20)
        X = np.stack([f[y0:y1] for f in stack]).astype(np.float32)
        E = np.stack([np.unpackbits(e[y0:y1], axis=1)[:, :S.W] for e in excl]).astype(bool)
        b0 = np.nanmedian(np.where(E[..., None], np.nan, X), 0)
        g, g0 = X.mean(3), np.nanmean(b0, 2)
        E2 = E | (g < DARK_REJECT * g0[None]) | (g > (2 - DARK_REJECT) * g0[None])
        bg[y0:y1] = np.nanmedian(np.where(E2[..., None], np.nan, X), 0)
        cnt[y0:y1] = (~E2).sum(0)
    hole = (cnt < HOLE_MIN_N) | ~np.isfinite(bg).all(2)
    bgf = np.nan_to_num(bg, nan=0).clip(0, 255).astype(np.uint8)
    filled = cv2.inpaint(bgf, hole.astype(np.uint8), 7, cv2.INPAINT_TELEA)
    cv2.imwrite(str(OUT / "bg_v2.png"), filled)
    cv2.imwrite(str(OUT / "bg_v2_hole.png"), hole.astype(np.uint8) * 255)
    # 机の面の絵 (appearance_337.table_textures と同じ写し方)
    xs = np.arange(A7.TEX_X_MM[0], A7.TEX_X_MM[1]) + 0.5
    ys = A7.TEX_Y_MM[1] - np.arange(A7.TEX_Y_MM[1] - A7.TEX_Y_MM[0]) - 0.5
    X, Yy = np.meshgrid(xs, ys)
    px = S.project_arm(np.c_[X.ravel(), Yy.ravel(), np.zeros(X.size)], cams["desk"]).reshape(X.shape + (2,)).astype(np.float32)
    inside = (px[..., 0] >= 0) & (px[..., 0] <= S.W - 1) & (px[..., 1] >= 0) & (px[..., 1] <= S.H - 1)
    tex = cv2.remap(filled, px[..., 0], px[..., 1], cv2.INTER_LINEAR, borderValue=0)
    tex[~inside] = 0
    hm = cv2.remap(hole.astype(np.uint8) * 255, px[..., 0], px[..., 1], cv2.INTER_NEAREST, borderValue=0)
    mk = np.where(inside, np.where(hm > 0, 128, 255), 0).astype(np.uint8)
    cv2.imwrite(str(OUT / "table_texture_v2.png"), tex)
    cv2.imwrite(str(OUT / "table_texture_v2_mask.png"), mk)
    gr = A7.gray(filled)[~hole]
    p5, p50, p95 = np.percentile(gr, [5, 50, 95])
    old = json.loads((HERE.parent / "check_337" / "summary_337.json").read_text())["desk_brightness"]
    scale = float(p50 / REF_GRAY)
    p = load()
    p["session_light_scale"] = {"value": round(scale, 3), "gray_p5_p50_p95": [round(float(p5), 1), round(float(p50), 1), round(float(p95), 1)],
                                "bgr_median": np.median(filled[~hole].reshape(-1, 3), 0).round(1).tolist(),
                                "old_sessions_gray_p5_p50_p95": {k: v["gray_p5_p50_p95"] for k, v in old.items()},
                                "source": f"依頼 362 appearance_362.py --bg: 新しい 50 本の机側 ({N} コマ. {BG_STEP} コマおき) の背景の灰色の中央値 "
                                          f"{p50:.1f} ÷ {REF_GRAY:.0f} (依頼 337 の pos23・pos45. pos1b の 0.834 と同じ決め方)"}
    p["table_texture"] = {"file": "so101/check_362/table_texture_v2.png", "mask": "so101/check_362/table_texture_v2_mask.png",
                          "bg": "so101/check_362/bg_v2.png", "frames": N, "hole_frac": round(float(hole.mean()), 4),
                          "seen_frac": round(float(inside.mean()), 3),
                          "source": f"依頼 362 appearance_362.py --bg: 50 本の机側 {N} コマの画素ごとの中央値 (2 回. 赤・80×80×45mm の箱を外す. "
                                    f"1 回目の {DARK_REJECT} 倍より暗い・{2 - DARK_REJECT:.2f} 倍より明るいコマを外す). 残りが {HOLE_MIN_N} コマより少ない所は埋めた. "
                                    "机の面 (z=0) へ 机側カメラで写した (appearance_337.table_textures と同じ)"}
    P = A3.load_params()["level1_color_exposure"]["camera_gain_bgr"]
    if "camera_gain_bgr" not in p:
        p["camera_gain_bgr"] = {"desk": P["desk"]["pos1b"], "wrist": (np.array(P["wrist"]["v1"]) / scale).round(3).tolist(),
                                "history": [], "source": "初めの値: 机側 = pos1b, 手首 = v1 ÷ 光の倍率 (まだ当てていない)"}
    p["time_bg"] = datetime.now().isoformat(timespec="seconds")
    save(p)
    print(json.dumps({k: p[k] for k in ("session_light_scale", "table_texture", "camera_gain_bgr")}, ensure_ascii=False, indent=1))


def gain_mode(tag):
    import pandas as pd
    fr = pd.concat([pd.read_csv(f) for f in sorted((OUT / tag).glob("ep*_frames.csv"))], ignore_index=True)
    p = load()
    g = p["camera_gain_bgr"]
    log = {}
    for cam in ("desk", "wrist"):
        c = fr.dropna(subset=[f"{cam}_table_real_B"])
        r = np.array([float(c[f"{cam}_table_real_{k}"].median() / max(1.0, c[f"{cam}_table_sim_{k}"].median())) for k in "BGR"])
        old = np.array(g[cam])
        g[cam] = (old * r).round(3).tolist()
        log[cam] = {"old": old.round(3).tolist(), "ratio_real_over_sim": r.round(3).tolist(), "new": g[cam], "frames": int(len(c)),
                    "episodes": int(c["new_episode_index"].nunique())}
    g["history"].append({"tag": tag, "time": datetime.now().isoformat(timespec="seconds"), **log})
    g["source"] = ("依頼 362 appearance_362.py --gain: 初めの値 (机側 = pos1b, 手首 = v1 ÷ 光の倍率) に simreplay_362 の 机 (table) の "
                   "実機 ÷ シム (B・G・R. コマの中央値) を掛けた (依頼 353 cal_353 と同じ). 掛けた回は history")
    save(p)
    print(json.dumps(log, ensure_ascii=False, indent=1))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--bg", action="store_true")
    ap.add_argument("--gain", action="store_true")
    ap.add_argument("--tag", default="")
    a = ap.parse_args()
    OUT.mkdir(parents=True, exist_ok=True)
    if a.bg:
        bg_mode()
    if a.gain:
        gain_mode(a.tag)


if __name__ == "__main__":
    main()
