# hdri to sofbox.py
bl_info = {
    "name": "HDRI2Softbox",
    "author": "Jonathan and Grok",
    "version": (1, 0, 47),
    "blender": (4, 3, 0),
    "location": "View3D > N-Panel > Softbox",
    "description": "Convert EXR/HDR images to softbox cube assets for lighting",
    "category": "Lighting"
}

import bpy
import pathlib
from bpy.types import Operator, Panel
from bpy.props import StringProperty

def create_emissive_material(file_path, name):
    mat = bpy.data.materials.new(name=name)
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links
    nodes.clear()

    tex = nodes.new("ShaderNodeTexImage")
    tex.location = (0, 0)
    tex.image = bpy.data.images.load(str(file_path))
    log_message(f"Setting color space to Linear Rec.709 for image: {file_path.name}")
    tex.image.colorspace_settings.name = "Linear Rec.709"
    tex.interpolation = "Smart"
    
    ramp_alpha = nodes.new("ShaderNodeValToRGB")
    ramp_alpha.location = (300, 50)

    ramp_emission = nodes.new("ShaderNodeValToRGB")
    ramp_emission.location = (300, -175)
    ramp_emission.mute = True  # Mute the ramp node to let original colors pass through by default
    bsdf = nodes.new("ShaderNodeBsdfPrincipled")
    bsdf.location = (600, 0)
    bsdf.inputs["Base Color"].default_value = (0, 0, 0, 1)
    bsdf.inputs["Roughness"].default_value = 1.0
    bsdf.inputs["Emission Strength"].default_value = 2.5

    output = nodes.new("ShaderNodeOutputMaterial")
    output.location = (900, 0)

    links.new(tex.outputs["Color"], ramp_emission.inputs["Fac"])
    links.new(ramp_emission.outputs["Color"], bsdf.inputs["Emission Color"])
    links.new(tex.outputs["Color"], ramp_alpha.inputs["Fac"])
    links.new(ramp_alpha.outputs["Color"], bsdf.inputs["Alpha"])
    links.new(bsdf.outputs["BSDF"], output.inputs["Surface"])

    return mat

def create_non_emissive_material():
    mat = bpy.data.materials.new(name="Softbox exterior")
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links
    nodes.clear()

    transparent = nodes.new("ShaderNodeBsdfTransparent")
    transparent.location = (0, 0)
    transparent.inputs["Color"].default_value = (1, 1, 1, 1)

    output = nodes.new("ShaderNodeOutputMaterial")
    output.location = (300, 0)

    links.new(transparent.outputs["BSDF"], output.inputs["Surface"])

    return mat

def build_softbox_cube(file_path, folder_path, emissive_mat, non_emissive_mat, index):
    img = bpy.data.images.load(str(file_path))
    aspect_ratio = img.size[0] / img.size[1] if img.size[1] != 0 else 1.0
    bpy.data.images.remove(img)

    unit_settings = bpy.context.scene.unit_settings
    inches_to_units = 0.0254  # 1 Blender unit = 1 meter, 1 inch = 0.0254 meters

    width = 36 * inches_to_units
    height = width / aspect_ratio
    depth = 10 * inches_to_units
    extra_depth = 5 * inches_to_units
    total_depth = depth + extra_depth

    top_width = width * 1.12
    top_height = height * 1.12

    mesh = bpy.data.meshes.new(name=file_path.stem)
    obj = bpy.data.objects.new(name=file_path.stem, object_data=mesh)
    bpy.context.collection.objects.link(obj)

    vertices = [
        # Base face (Y=0, smaller)
        (-width/2, 0, 0),      # 0: Bottom-left
        (width/2, 0, 0),       # 1: Bottom-right
        (width/2, 0, height),  # 2: Top-right
        (-width/2, 0, height), # 3: Top-left
        # Middle face (Y=-depth, larger)
        (-top_width/2, -depth, 0),      # 4: Bottom-left
        (top_width/2, -depth, 0),       # 5: Bottom-right
        (top_width/2, -depth, top_height),  # 6: Top-right
        (-top_width/2, -depth, top_height), # 7: Top-left
        # Top face (Y=-(depth+extra_depth), same size as middle)
        (-top_width/2, -total_depth, 0),      # 8: Bottom-left
        (top_width/2, -total_depth, 0),       # 9: Bottom-right
        (top_width/2, -total_depth, top_height),  # 10: Top-right
        (-top_width/2, -total_depth, top_height)  # 11: Top-left
    ]
    faces = [
        (0, 1, 2, 3),      # Base face (Y=0)
        (4, 5, 6, 7),      # Middle face (Y=-depth)
        (8, 9, 10, 11),    # Top face (Y=-(depth+extra_depth))
        (0, 1, 5, 4),      # Bottom side (Y=0 to Y=-depth)
        (1, 2, 6, 5),      # Right side (Y=0 to Y=-depth)
        (2, 3, 7, 6),      # Top side (Y=0 to Y=-depth)
        (3, 0, 4, 7),      # Left side (Y=0 to Y=-depth)
        (4, 5, 9, 8),      # Bottom side (Y=-depth to Y=-(depth+extra_depth))
        (5, 6, 10, 9),     # Right side (Y=-depth to Y=-(depth+extra_depth))
        (6, 7, 11, 10),    # Top side (Y=-depth to Y=-(depth+extra_depth))
        (7, 4, 8, 11)      # Left side (Y=-depth to Y=-(depth+extra_depth))
    ]

    mesh.from_pydata(vertices, [], faces)
    mesh.update()

    obj.data.materials.append(emissive_mat)
    obj.data.materials.append(non_emissive_mat)

    for poly in mesh.polygons:
        y_positions = [mesh.vertices[vert].co.y for vert in poly.vertices]
        y_min = min(y_positions)
        y_max = max(y_positions)
        if abs(y_min) < 0.001 and abs(y_max) < 0.001:
            poly.material_index = 1  # Non-emissive
        elif abs(y_min + total_depth) < 0.01 and abs(y_max + total_depth) < 0.01:
            poly.material_index = 0  # Emissive
        else:
            poly.material_index = 1  # Sides

    obj.color = (1.0, 0.753, 0.0, 1.0)
    obj.rotation_euler = (0, 0, 0)
    obj.scale = (1, 1, 1)
    obj.location.x = index * (46 * inches_to_units)

    # Set wireframe display
    obj.show_wire = True
    obj.display_type = 'WIRE'

    # Add UV layer
    if not mesh.uv_layers:
        uv_layer = mesh.uv_layers.new()
        # Manually adjust UV mapping for the top face to align with image orientation
        for poly in mesh.polygons:
            y_positions = [mesh.vertices[vert].co.y for vert in poly.vertices]
            y_min = min(y_positions)
            y_max = max(y_positions)
            if abs(y_min + total_depth) < 0.01 and abs(y_max + total_depth) < 0.01:  # Top face
                for loop_index in poly.loop_indices:
                    loop = mesh.loops[loop_index]
                    vert_idx = loop.vertex_index
                    # Get the vertex position
                    x, y, z = vertices[vert_idx]
                    # Map to UV space (normalize to 0-1 range)
                    # Image's horizontal bars (X-axis) should align with cube's X-axis (width)
                    # Image's vertical axis (Y) should align with cube's Z-axis (height)
                    u = (x + top_width/2) / top_width  # X-axis maps to U (image X)
                    v = (z - 0) / top_height  # Z-axis maps to V (image Y)
                    uv_layer.data[loop_index].uv = (u, v)

    # Mark as asset (thumbnails will be handled by external add-ons)
    obj.asset_mark()

    return obj

def log_message(message, level="INFO"):
    print(f"[HDRI2Softbox] {level}: {message}")

def convert_exr_hdr_to_softbox(folder_path):
    log_message(f"Starting file scan in: {folder_path}")
    successes = 0
    fails = 0
    non_emissive_mat = None

    folder = pathlib.Path(folder_path)
    files = list(folder.glob("*.[eE][xX][rR]")) + list(folder.glob("*.[hH][dD][rR]"))
    unique_files = sorted(list(set(files)), key=lambda x: x.name.lower())  # Sort alphabetically (case-insensitive)
    log_message(f"Found {len(unique_files)} potential EXR/HDR files")
    for file in unique_files:
        log_message(f"Detected file: {file.name}")

    if not unique_files:
        log_message("No EXR/HDR files found", "ERROR")
        return {"successes": 0, "fails": 0}

    for index, file in enumerate(unique_files):
        try:
            log_message(f"Processing file: {file.name}")
            emissive_mat = create_emissive_material(file, file.stem)
            if not non_emissive_mat:
                non_emissive_mat = create_non_emissive_material()

            obj = build_softbox_cube(file, folder_path, emissive_mat, non_emissive_mat, index)

            successes += 1
            log_message(f"Success: Converted {file.stem}")
        except Exception as e:
            fails += 1
            log_message(f"Failed: {file.stem} ({str(e)})", "ERROR")

    log_message(f"Summary: {successes} successes, {fails} fails")
    return {"successes": successes, "fails": fails}

# Operator
class SoftboxConverterOperator(Operator):
    bl_idname = "object.softbox_converter"
    bl_label = "Select Folder"
    bl_options = {"REGISTER", "UNDO"}

    filepath: StringProperty(
        name="Folder Path",
        subtype="DIR_PATH",
        default=""
    )
    directory: StringProperty(
        name="Directory",
        subtype="DIR_PATH",
        default=""
    )

    def execute(self, context):
        filepath = pathlib.Path(self.directory)
        log_message(f"Raw directory from browser: '{self.directory}'")

        folder = str(filepath)
        log_message(f"Adjusted folder path: '{folder}'")
        log_message(f"Executing with folder path: '{folder}'")

        if not folder:
            log_message("Folder path is empty", "ERROR")
            self.report({"ERROR"}, "No folder selected")
            return {"CANCELLED"}

        folder_path = pathlib.Path(folder)
        if not folder_path.is_dir():
            log_message(f"Invalid folder: '{folder}' is not a directory", "ERROR")
            self.report({"ERROR"}, f"Invalid folder: '{folder}'")
            return {"CANCELLED"}

        result = convert_exr_hdr_to_softbox(folder_path)
        if result["successes"] == 0 and result["fails"] == 0:
            self.report({"ERROR"}, "No EXR/HDR files found")
        else:
            self.report({"INFO"}, f"Converted {result['successes']} softboxes")
        return {"FINISHED"}

    def invoke(self, context, event):
        log_message("Opening folder selection dialog")
        self.directory = bpy.utils.user_resource('SCRIPTS', path="") or ""
        self.filepath = ""
        context.window_manager.fileselect_add(self)
        return {"RUNNING_MODAL"}

# Panel
class SoftboxConverterPanel(Panel):
    bl_label = "HDRI2Softbox"
    bl_idname = "VIEW3D_PT_softbox_converter"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_category = "Softbox"

    def draw(self, context):
        layout = self.layout
        layout.operator("object.softbox_converter", text="Select Folder")

# Registration
classes = (
    SoftboxConverterPanel,
    SoftboxConverterOperator,
)

def register():
    for cls in classes:
        bpy.utils.register_class(cls)

def unregister():
    for cls in reversed(classes):
        bpy.utils.unregister_class(cls)

if __name__ == "__main__":
    register()