"""OpticRig: export the active Blender camera to camera_track.json (format version 1).

In Blender: open the Scripting tab, open this file, press Run Script.
camera_track.json is written next to your saved .blend file.

From the command line:
    blender scene.blend --background --python export_camera_track.py -- [--out path.json]

Format (Y-up, as in Three.js and glTF):
    {
      "version": 1,
      "fps": 24,
      "aspect": 1.7778,
      "frames": [
        {"frame": 1, "t": 0.0, "pos": [x, y, z], "quat": [x, y, z, w], "fov": 39.6}
      ]
    }
pos and quat are the camera world transform, quat is in x, y, z, w order,
fov is the vertical field of view in degrees (same as PerspectiveCamera.fov in Three.js),
t is seconds from the first frame.

https://opticrig.eu
"""

import json
import math
import os
import sys

import bpy
from mathutils import Matrix

FORMAT_VERSION = 1

# Blender is Z-up, Three.js and glTF are Y-up.
# Rotating -90 degrees around X maps (x, y, z) to (x, z, -y).
AXIS_CONV = Matrix.Rotation(math.radians(-90.0), 4, "X")


class ExportError(Exception):
    """A problem the user can fix in the scene."""


def render_aspect(scene):
    r = scene.render
    return (r.resolution_x * r.pixel_aspect_x) / (r.resolution_y * r.pixel_aspect_y)


def vertical_fov(cam_data, aspect):
    """Vertical field of view in radians, matching what Blender renders."""
    fit = cam_data.sensor_fit
    if fit == "AUTO":
        horizontal = aspect >= 1.0
        sensor = cam_data.sensor_width  # AUTO fits the sensor width to the longer side
    elif fit == "HORIZONTAL":
        horizontal = True
        sensor = cam_data.sensor_width
    else:  # VERTICAL
        horizontal = False
        sensor = cam_data.sensor_height

    angle = 2.0 * math.atan(sensor / (2.0 * cam_data.lens))
    if horizontal:
        return 2.0 * math.atan(math.tan(angle / 2.0) / aspect)
    return angle


def check_camera(scene):
    cam = scene.camera
    if cam is None:
        raise ExportError(
            "The scene has no active camera. Select your camera and choose "
            "View > Cameras > Set Active Object as Camera (Ctrl+Numpad 0)."
        )
    if cam.type != "CAMERA":
        raise ExportError(f"The active camera '{cam.name}' is not a camera object.")
    if cam.data.type == "ORTHO":
        raise ExportError(
            f"Camera '{cam.name}' is orthographic. Only perspective cameras are supported "
            "(Camera > Lens > Type: Perspective)."
        )
    if cam.data.type != "PERSP":
        raise ExportError(
            f"Camera '{cam.name}' has type {cam.data.type}. Only perspective cameras are supported."
        )
    if scene.frame_end < scene.frame_start:
        raise ExportError("The frame range ends before it starts. Check Frame Start and End.")
    return cam


def default_out_path():
    if not bpy.data.filepath:
        raise ExportError(
            "The project is not saved yet, so there is no folder to write camera_track.json to. "
            "Save the .blend file (File > Save) and run the script again."
        )
    return bpy.path.abspath("//camera_track.json")


def collect_track(scene):
    """Return (track, warnings). track is a dict in the camera_track.json format. Writes nothing."""
    cam = check_camera(scene)
    aspect = render_aspect(scene)
    fps = scene.render.fps / scene.render.fps_base

    frames = []
    warnings = []
    scaled = False
    original_frame = scene.frame_current
    try:
        for f in range(scene.frame_start, scene.frame_end + 1):
            scene.frame_set(f)
            data = cam.data
            if abs(data.shift_x) > 1e-6 or abs(data.shift_y) > 1e-6:
                raise ExportError(
                    f"Camera '{cam.name}' uses lens shift (Shift X={data.shift_x:.3f}, "
                    f"Y={data.shift_y:.3f}) at frame {f}. Three.js cannot reproduce this framing directly. "
                    "Set Shift to 0."
                )
            loc, rot, scale = (AXIS_CONV @ cam.matrix_world).decompose()
            if not scaled and any(abs(s - 1.0) > 1e-4 for s in scale):
                scaled = True
                warnings.append(
                    f"The camera is scaled ({scale.x:.3f}, {scale.y:.3f}, {scale.z:.3f}). "
                    "Scale was ignored, the framing should not change."
                )
            fov = math.degrees(vertical_fov(data, aspect))
            frames.append({
                "frame": f,
                "t": round((f - scene.frame_start) / fps, 4),
                "pos": [round(loc.x, 5), round(loc.y, 5), round(loc.z, 5)],
                "quat": [round(rot.x, 6), round(rot.y, 6), round(rot.z, 6), round(rot.w, 6)],
                "fov": round(fov, 3),
            })
    finally:
        scene.frame_set(original_frame)

    if len(frames) > 1 and all(
        fr["pos"] == frames[0]["pos"] and fr["quat"] == frames[0]["quat"] and fr["fov"] == frames[0]["fov"]
        for fr in frames
    ):
        warnings.append("The camera does not move in any frame. Check that the animation is set up.")

    fps_out = int(fps) if float(fps).is_integer() else round(fps, 4)
    track = {"version": FORMAT_VERSION, "fps": fps_out, "aspect": round(aspect, 4), "frames": frames}
    return track, warnings


def export_camera_track(scene=None, out_path=None):
    scene = scene or bpy.context.scene
    out_path = out_path or default_out_path()
    track, warnings = collect_track(scene)
    os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
    with open(out_path, "w", encoding="utf-8", newline="\n") as fp:
        json.dump(track, fp, indent=2)
    for w in warnings:
        print(f"OpticRig: warning: {w}")
    print(f"OpticRig: wrote {len(track['frames'])} frames to {out_path}")
    return out_path, track, warnings


def _cli_out_path():
    argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
    if "--out" in argv:
        return argv[argv.index("--out") + 1]
    return None


def _report(title, message, icon):
    print(f"OpticRig: {title}: {message}")
    if not bpy.app.background:
        def draw(menu, _context):
            menu.layout.label(text=message)
        bpy.context.window_manager.popup_menu(draw, title=f"OpticRig: {title}", icon=icon)


if __name__ == "__main__":
    try:
        path, exported, _ = export_camera_track(out_path=_cli_out_path())
        if not bpy.app.background:
            _report("done", f"Wrote {len(exported['frames'])} frames to {path}", "CHECKMARK")
    except ExportError as exc:
        _report("export stopped", str(exc), "ERROR")
        if bpy.app.background:
            sys.exit(1)
