"""Render protected sparse replay evidence from a submitted Blender scene."""

import bpy
import json
import sys
from pathlib import Path
from mathutils import Vector


argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
scene_path, output_dir, config_path = argv
config = json.loads(Path(config_path).read_text())
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)

bpy.ops.wm.open_mainfile(filepath=str(Path(scene_path).resolve()))
scene = bpy.context.scene

if not scene.camera:
    points = []
    for obj in bpy.data.objects:
        if obj.type == "MESH" and not obj.hide_render:
            points.extend(obj.matrix_world @ Vector(corner) for corner in obj.bound_box)
    if not points:
        raise RuntimeError("No visible mesh geometry and no camera")
    lo = Vector((min(p[i] for p in points) for i in range(3)))
    hi = Vector((max(p[i] for p in points) for i in range(3)))
    center = (lo + hi) / 2
    cam_data = bpy.data.cameras.new("ProtectedEvaluatorCamera")
    cam = bpy.data.objects.new("ProtectedEvaluatorCamera", cam_data)
    bpy.context.collection.objects.link(cam)
    height = max(hi.z - lo.z, 1.0)
    cam.location = center + Vector((height * 1.15, -height * 2.3, height * 0.35))
    cam.rotation_euler = (center - cam.location).to_track_quat("-Z", "Y").to_euler()
    cam_data.type = "ORTHO"
    cam_data.ortho_scale = height * 1.25
    scene.camera = cam
    fallback = True
else:
    fallback = False

# Preserve the submitted render engine and scene appearance. Consistency is
# perceptual and compression-tolerant; the evaluator does not force Eevee.
scene.render.resolution_x, scene.render.resolution_y = config["replay_comparison"]["resolution"]
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = "PNG"
scene.render.film_transparent = False

rendered = []
for frame in config["replay_comparison"]["sample_frames"]:
    scene.frame_set(frame)
    scene.render.filepath = str(out / f"replay_{frame:04d}.png")
    bpy.ops.render.render(write_still=True)
    rendered.append(scene.render.filepath)

(out / "replay_manifest.json").write_text(json.dumps({
    "scene": str(Path(scene_path).resolve()),
    "fresh_process_open": True,
    "camera": scene.camera.name,
    "camera_fallback": fallback,
    "frames": config["replay_comparison"]["sample_frames"],
    "resolution": config["replay_comparison"]["resolution"],
    "files": rendered,
}, indent=2))
print(f"[replay] {len(rendered)} frames -> {out}")
