"""Light the active scene with a local equirectangular HDR or EXR image."""
from pathlib import Path

import bpy

# // means relative to the saved .blend. An absolute path also works.
IMAGE_PATH = "//assets/hdri/studio.exr"
STRENGTH = 0.8

if IMAGE_PATH.startswith("//") and not bpy.data.is_saved:
    raise ValueError("Save the .blend before using a // path, or use an absolute path.")
path = Path(bpy.path.abspath(IMAGE_PATH)).expanduser()
if not path.is_absolute() or not path.is_file() or path.suffix.lower() not in {".hdr", ".exr"}:
    raise FileNotFoundError(f"Set IMAGE_PATH to an existing .hdr or .exr file: {path}")
if STRENGTH < 0:
    raise ValueError("Use a nonnegative value for STRENGTH.")

# Load the file before changing the scene.
image = bpy.data.images.load(str(path), check_existing=True)
scene = bpy.context.scene
world = scene.world

if world and world.get("rp_hdri_world") and world.users - int(world.use_fake_user) == 1:
    tree = world.node_tree
    if tree is None:
        raise ValueError("Choose another World before rebuilding the HDRI setup.")
    environment = tree.nodes.get("RP Environment")
    background = tree.nodes.get("RP Background")
    if (environment is None or environment.type != "TEX_ENVIRONMENT"
            or background is None or background.type != "BACKGROUND"):
        raise ValueError("Choose another World before rebuilding the HDRI setup.")
else:
    world = bpy.data.worlds.new("RP HDRI World")
    world["rp_hdri_world"] = True
    world.use_nodes = True
    tree = world.node_tree
    tree.nodes.clear()
    environment = tree.nodes.new("ShaderNodeTexEnvironment")
    environment.name = "RP Environment"
    environment.location = (-320, 0)
    background = tree.nodes.new("ShaderNodeBackground")
    background.name = "RP Background"
    background.location = (0, 0)
    output = tree.nodes.new("ShaderNodeOutputWorld")
    output.location = (240, 0)
    tree.links.new(environment.outputs["Color"], background.inputs["Color"])
    tree.links.new(background.outputs["Background"], output.inputs["Surface"])

environment.image = image
environment.projection = "EQUIRECTANGULAR"
background.inputs["Strength"].default_value = STRENGTH
scene.world = world
print(f"HDRI ready: {path.name} at strength {STRENGTH}.")
