"""依頼 360: Blender (Cycles) で 試しの場面を 画面なしで 1 コマ描き, 時間を測る.

使い方 (Blender の中で動かす):
  blender -b --factory-startup --python so101/check_360/bench_360.py -- --device GPU
  blender -b --factory-startup --python so101/check_360/bench_360.py -- --device CPU

場面 (アームの座標・mm → Blender は m):
  机の平面・白い箱 (外寸 86.1×82.7mm・高さ 45mm・壁 3mm・半透明の白)・赤いブロック (一辺 21.7mm = scene_334 の中央値)
  柔らかい面光源 1 つ + 部屋全体の柔らかい光. アームは入れない.
カメラ:
  机側 = camera_desk.json の内側の値 + desk_pose.json の向き・位置 (sim_330.load_cameras と同じ計算). 歪みは入れない.
  手首 = camera_wrist.json の内側の値. 位置は試しに ブロックの上 (つかむ前の高さの目安) に置いた. 本物の手首の位置は次の依頼.
KIOXIA は読むだけ. 書くのは so101/check_360/ だけ.
"""
import json
import math
import statistics
import sys
import time
from pathlib import Path

import bpy
from mathutils import Matrix, Vector

HERE = Path(__file__).resolve().parent
KIOXIA_CAM = Path("/Volumes/KIOXIA/r2r2r-data/so101_calibration/2026-11-27/cameras")
SAMPLES = (32, 64, 128)
REPEAT = 2  # 1 通りあたり 何回測るか (最初の 1 回の前に 準備の 1 コマを別に描く)

BLOCK_MM = 21.7
BLOCK_XY = (374.8, -42.7)  # scene_334 の episode 0
BLOCK_YAW = -0.1
BOX_XY = (195.6, -175.2)  # scene_334 box_330
BOX_YAW = 5.0
BOX_OUT = (86.1, 82.7)
BOX_H = 45.0
BOX_WALL = 3.0


def arg(name, default):
    a = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
    return a[a.index(name) + 1] if name in a else default


def mm(v):
    return [x / 1000 for x in v]


def mat_principled(name, color, rough, **kw):
    m = bpy.data.materials.new(name)
    m.use_nodes = True
    b = m.node_tree.nodes["Principled BSDF"]
    b.inputs["Base Color"].default_value = (*color, 1)
    b.inputs["Roughness"].default_value = rough
    for k, v in kw.items():
        b.inputs[k].default_value = v
    return m


def add_box(name, center_mm, size_mm, yaw_deg, mat, parent=None):
    bpy.ops.mesh.primitive_cube_add(size=1, location=mm(center_mm))
    o = bpy.context.object
    o.name = name
    o.scale = mm(size_mm)
    o.rotation_euler = (0, 0, math.radians(yaw_deg))
    o.data.materials.append(mat)
    if parent is not None:
        o.parent = parent
    return o


def build_scene():
    bpy.ops.wm.read_factory_settings(use_empty=True)
    sc = bpy.context.scene

    table = mat_principled("table", (0.42, 0.40, 0.37), 0.65)
    red = mat_principled("block", (0.75, 0.02, 0.03), 0.45)
    # 半透明の白: 表面下の散らし (subsurface) で 壁の向こうの光が透ける
    white = mat_principled("box", (0.92, 0.92, 0.90), 0.45,
                           **{"Subsurface Weight": 0.8, "Subsurface Scale": 0.004})

    add_box("table", (300, 0, -5), (1200, 1200, 10), 0, table)
    add_box("block", (*BLOCK_XY, BLOCK_MM / 2), (BLOCK_MM,) * 3, BLOCK_YAW, red)

    # 箱: 箱の中心に空の親を置き, 床と 4 枚の壁を子にする
    bpy.ops.object.empty_add(location=mm((*BOX_XY, 0)))
    box = bpy.context.object
    box.name = "box"
    box.rotation_euler = (0, 0, math.radians(BOX_YAW))
    lx, ly, h, t = BOX_OUT[0], BOX_OUT[1], BOX_H, BOX_WALL
    add_box("box_floor", (0, 0, t / 2), (lx, ly, t), 0, white, box)
    add_box("box_wall_xn", (-lx / 2 + t / 2, 0, h / 2), (t, ly, h), 0, white, box)
    add_box("box_wall_xp", (lx / 2 - t / 2, 0, h / 2), (t, ly, h), 0, white, box)
    add_box("box_wall_yn", (0, -ly / 2 + t / 2, h / 2), (lx - 2 * t, t, h), 0, white, box)
    add_box("box_wall_yp", (0, ly / 2 - t / 2, h / 2), (lx - 2 * t, t, h), 0, white, box)

    # 柔らかい面光源 1 つ (机の上 1m・60cm 四方)
    ld = bpy.data.lights.new("softbox", type="AREA")
    ld.shape = "SQUARE"
    ld.size = 0.6
    ld.energy = 12.0
    lo = bpy.data.objects.new("softbox", ld)
    lo.location = mm((250, -50, 1000))
    sc.collection.objects.link(lo)

    # 部屋全体の柔らかい光
    w = bpy.data.worlds.new("room")
    w.use_nodes = True
    w.node_tree.nodes["Background"].inputs["Color"].default_value = (0.8, 0.8, 0.8, 1)
    w.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.08
    sc.world = w
    return sc


def add_camera(sc, name, K, size, R_cv, pos_mm):
    """OpenCV の内側の値 K と 向き R_cv (列 = カメラの x右・y下・z前 をアームの座標で) から Blender のカメラ."""
    W, H = size
    cd = bpy.data.cameras.new(name)
    cd.sensor_fit = "HORIZONTAL"
    cd.sensor_width = 36.0
    cd.lens = K[0][0] * 36.0 / W
    cd.shift_x = -(K[0][2] - W / 2) / W
    cd.shift_y = (K[1][2] - H / 2) / W
    cd.clip_start = 0.005
    co = bpy.data.objects.new(name, cd)
    sc.collection.objects.link(co)
    x, y, z = (Vector([R_cv[i][j] for i in range(3)]) for j in range(3))
    Rb = Matrix((x, -y, -z)).transposed()  # Blender のカメラは x右・y上・-z前
    co.matrix_world = Matrix.Translation(Vector(mm(pos_mm))) @ Rb.to_4x4()
    # fx と fy の差 (0.3% ほど) は 縦の画素の比で合わせる
    return co, K[1][1] / K[0][0]


def look_at(eye, target, up=(0, 0, 1)):
    """目の位置から target を向く OpenCV の向き (列 = x右・y下・z前)."""
    z = (Vector(target) - Vector(eye)).normalized()
    x = z.cross(Vector(up)).normalized()
    y = z.cross(x)
    return [[x[i], y[i], z[i]] for i in range(3)]


def cameras(sc):
    camd = json.loads((KIOXIA_CAM / "camera_desk.json").read_text())
    camw = json.loads((KIOXIA_CAM / "camera_wrist.json").read_text())
    pose = json.loads((KIOXIA_CAM / "desk_pose.json").read_text())["pose_all_frames_together"]
    A = json.loads((KIOXIA_CAM / "arm_frame_v2.json").read_text())["derived_mm"]["origin_A_in_arm_frame"]
    pos_d = [A[i] + pose["cam_pos_mm"][i] for i in range(3)]
    desk = add_camera(sc, "desk", camd["camera_matrix"], camd["image_size"], pose["R_cam_in_board"], pos_d)
    # 手首 (試しの置き方): ブロックの上 120mm・腕の根元側に 60mm 引いた所から ブロックを見下ろす
    eye = (BLOCK_XY[0] - 60, BLOCK_XY[1], 120)
    R_w = look_at(eye, (BLOCK_XY[0] + 10, BLOCK_XY[1], 0), up=(1, 0, 0))
    wrist = add_camera(sc, "wrist", camw["camera_matrix"], camw["image_size"], R_w, eye)
    return {"desk": (desk, camd["image_size"]), "wrist": (wrist, camw["image_size"])}


def set_device(sc, dev):
    sc.render.engine = "CYCLES"
    cy = sc.cycles
    prefs = bpy.context.preferences.addons["cycles"].preferences
    if dev == "GPU":
        prefs.compute_device_type = "METAL"
        prefs.get_devices()
        for d in prefs.devices:
            d.use = d.type == "METAL"
        cy.device = "GPU"
    else:
        prefs.compute_device_type = "NONE"
        cy.device = "CPU"
    used = [d.name for d in prefs.devices if d.use] if dev == "GPU" else ["CPU"]
    return used


def render_once(sc, cam, size, samples, out_png):
    sc.camera = cam[0]
    sc.render.resolution_x, sc.render.resolution_y = size
    sc.render.resolution_percentage = 100
    sc.render.pixel_aspect_x, sc.render.pixel_aspect_y = 1.0, cam[1]
    sc.cycles.samples = samples
    sc.cycles.use_adaptive_sampling = False
    sc.cycles.use_denoising = True
    sc.cycles.denoiser = "OPENIMAGEDENOISE"
    sc.cycles.denoising_use_gpu = sc.cycles.device == "GPU"
    sc.render.filepath = str(out_png)
    t0 = time.perf_counter()
    bpy.ops.render.render(write_still=True)
    return time.perf_counter() - t0


def main():
    dev = arg("--device", "GPU")
    sc = build_scene()
    cams = cameras(sc)
    used = set_device(sc, dev)
    sc.render.image_settings.file_format = "PNG"
    sc.render.use_persistent_data = True  # 続けて描くとき 場面の作り直しを省く (動画を描くときと同じ)
    out = HERE / "renders"
    out.mkdir(exist_ok=True)

    t_warm = render_once(sc, cams["desk"][0], cams["desk"][1], 1, out / f"_warm_{dev}.png")
    res = {"device": dev, "devices_used": used, "warmup_s": round(t_warm, 3), "runs": []}
    for key in ("desk", "wrist"):
        cam, size = cams[key]
        for s in SAMPLES:
            ts = [render_once(sc, cam, size, s, out / f"{key}_{dev}_s{s}.png") for _ in range(REPEAT)]
            r = {"camera": key, "size": list(size), "samples": s, "times_s": [round(t, 3) for t in ts],
                 "median_s": round(statistics.median(ts), 3)}
            print("RESULT", json.dumps(r), flush=True)
            res["runs"].append(r)
    (out / f"_warm_{dev}.png").unlink(missing_ok=True)
    res["blender"] = bpy.app.version_string
    (HERE / f"times_{dev}.json").write_text(json.dumps(res, ensure_ascii=False, indent=2))


main()
