"""依頼 370: render_368.py を そのまま Runpod の Linux の GPU (OptiX か CUDA) で動かす.
render_368.py の中身は変えずに読み込み, set_device (Metal 決め打ち) だけを OptiX → CUDA に差し替える. 値は全部 look_blender_v1.json のまま.
時間: 場面の組み立て (build)・GPU の用意 (set_device)・コマごと (times_<tag>.json は render_368 のとおり)・全部 を timing_370.json に書く.

使い方 (Blender の中. so101/ の形のまま置いた所で):
  blender -b --factory-startup --python so101/blender/render_370.py -- --src check_361/ep00 --out check_370/ep00 --tag pod [--device OPTIX]
"""
import hashlib
import json
import sys
import time
from pathlib import Path

T_START = time.perf_counter()
HERE = Path(__file__).resolve().parent
SRC368 = HERE / "render_368.py"


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


code = SRC368.read_text()
body, last = code.rstrip().rsplit("\n", 1)
assert last.strip() == "main()", "render_368.py の最後の行が main() でない"
ns = {"__file__": str(SRC368), "__name__": "render_368"}
t0 = time.perf_counter()
exec(compile(body, str(SRC368), "exec"), ns)  # 定義だけ (main は呼ばない)
T = {"import_368_s": round(time.perf_counter() - t0, 3)}

WANT = arg("--device", "OPTIX")


def set_device(sc):
    """render_368.set_device と同じ設定で, 装置だけを OptiX (なければ CUDA) にする."""
    import bpy
    R = ns["LOOK"]["render"]
    sc.render.engine = R["engine"]
    prefs = bpy.context.preferences.addons["cycles"].preferences
    kinds = [WANT] + [k for k in ("OPTIX", "CUDA") if k != WANT]
    for kind in kinds:
        try:
            prefs.compute_device_type = kind
        except TypeError:
            continue
        prefs.get_devices()
        devs = [d for d in prefs.devices if d.type == kind]
        if devs:
            break
    else:
        raise RuntimeError("OptiX も CUDA も見つからない")
    for d in prefs.devices:
        d.use = d.type == kind
    T["device_type"] = kind
    sc.cycles.device = "GPU"
    cy = sc.cycles
    cy.use_adaptive_sampling = R["adaptive_sampling"]
    cy.use_denoising = True
    cy.denoiser = "OPENIMAGEDENOISE"
    cy.denoising_use_gpu = True
    cy.max_bounces, cy.diffuse_bounces, cy.glossy_bounces, cy.transmission_bounces = (
        R["max_bounces"], R["diffuse_bounces"], R["glossy_bounces"], R["transmission_bounces"])
    cy.caustics_reflective = cy.caustics_refractive = R["caustics"]
    return [d.name for d in prefs.devices if d.use]


def timed(name, fn):
    def w(*a, **k):
        t = time.perf_counter()
        r = fn(*a, **k)
        T[name] = round(time.perf_counter() - t, 3)
        return r
    return w


ns["set_device"] = timed("set_device_s", set_device)
ns["build"] = timed("build_s", ns["build"])
t0 = time.perf_counter()
ns["main"]()
T["main_s"] = round(time.perf_counter() - t0, 3)
T["total_in_blender_s"] = round(time.perf_counter() - T_START, 3)
T["render_368_sha256"] = hashlib.sha256(SRC368.read_bytes()).hexdigest()
T["look_sha256"] = hashlib.sha256(ns["LOOK_PATH"].read_bytes()).hexdigest()
out = ns["SO101"] / arg("--out", "check_370/ep00")
(out / "timing_370.json").write_text(json.dumps(T, indent=1, ensure_ascii=False))
print("TIMING", json.dumps(T, ensure_ascii=False), flush=True)
