"""Set up a full-sphere monoscopic Cycles camera in the active scene."""
import math

import bpy

CAMERA_LOCATION = (0.0, 0.0, 1.65)
HEADING_DEGREES = 0.0
WIDTH = 2048

if WIDTH < 4 or WIDTH % 2:
    raise ValueError("Use an even image width to keep an exact 2:1 panorama.")

scene = bpy.context.scene
scene.render.engine = "CYCLES"
camera = next(
    (
        obj for obj in scene.objects
        if obj.type == "CAMERA" and obj.get("rp_panorama_camera") and len(obj.users_scene) == 1
    ),
    None,
)
if camera is None:
    optics = bpy.data.cameras.new("RP Panorama")
    camera = bpy.data.objects.new("RP Panorama", optics)
    scene.collection.objects.link(camera)
    camera["rp_panorama_camera"] = True
elif camera.data.users > 1:
    camera.data = camera.data.copy()

camera.location = CAMERA_LOCATION
camera.rotation_mode = "XYZ"
camera.rotation_euler = (math.pi / 2, 0, math.radians(HEADING_DEGREES - 90))
optics = camera.data
optics.type = "PANO"
optics.panorama_type = "EQUIRECTANGULAR"
optics.latitude_min = -math.pi / 2
optics.latitude_max = math.pi / 2
optics.longitude_min = -math.pi
optics.longitude_max = math.pi
scene.camera = camera

scene.render.resolution_x = WIDTH
scene.render.resolution_y = WIDTH // 2
scene.render.resolution_percentage = 100
scene.render.pixel_aspect_x = 1
scene.render.pixel_aspect_y = 1
scene.render.use_border = False
scene.render.use_multiview = False
print(f"Panorama ready: {WIDTH} × {WIDTH // 2}, Cycles, full sphere.")
