# ------------------------------------------------------------
# HDRI Helper – v2.9.5 – FINAL WITH PROGRESS BAR + CURSOR
# Author: Jonathan & Grok
# Version: 2.9.5
# ------------------------------------------------------------

bl_info = {
    "name": "HDRI Helper",
    "author": "Jonathan & Grok",
    "version": (2, 9, 5),
    "blender": (5, 0, 0),
    "category": "World",
    "description": "Pro HDRI tool – one world, perfect progress",
}

import bpy
import os
from bpy.props import StringProperty, BoolProperty, PointerProperty
from bpy.types import Operator, Panel, PropertyGroup


class HDRIWorldProps(PropertyGroup):
    hdri_path: StringProperty(name="HDRI Path")
    use_background: BoolProperty(
        name="Use Separate Background HDRI",
        default=False,
        update=lambda self, context: rebuild_world_nodes(context.scene.world)
    )
    background_hdri: PointerProperty(
        name="Background HDRI",
        type=bpy.types.World,
        update=lambda self, context: rebuild_world_nodes(context.scene.world)
    )
    main_node_group: PointerProperty(type=bpy.types.NodeTree)


# ─────────────────────────────────────────────────────────────
# NUCLEAR FIX – one world forever
# ─────────────────────────────────────────────────────────────
def nuke_default_world(scene, depsgraph):
    if getattr(scene, "_hdri_default_nuked", False):
        return
    scene._hdri_default_nuked = True

    default = bpy.data.worlds.get("World")
    if default and not hasattr(default, "hdri_props"):
        print("HDRI Helper")
        bpy.data.worlds.remove(default, do_unlink=True)

    world = scene.world
    if world and "." in world.name and world.name.rsplit(".", 1)[-1].isdigit():
        base = world.name.rsplit(".", 1)[0]
        orig = bpy.data.worlds.get(base)
        if orig and hasattr(orig, "hdri_props"):
            scene.world = orig

def register_handler():
    if nuke_default_world not in bpy.app.handlers.depsgraph_update_post:
        bpy.app.handlers.depsgraph_update_post.append(nuke_default_world)

def unregister_handler():
    if nuke_default_world in bpy.app.handlers.depsgraph_update_post:
        bpy.app.handlers.depsgraph_update_post.remove(nuke_default_world)


# ─────────────────────────────────────────────────────────────
# Your perfect code + PROGRESS BAR + CURSOR
# ─────────────────────────────────────────────────────────────
def title_case_hdri_name(filepath: str) -> str:
    name = bpy.path.display_name_from_filepath(filepath)
    name = name.replace("_", " ")
    parts = name.split()
    result = []
    for part in parts:
        if part.upper() in {"1K", "2K", "4K", "8K", "16K"}:
            result.append(part.upper())
        else:
            result.append(part.capitalize())
    return " ".join(result)


def create_hdri_node_group(name_suffix=""):
    ng_name = f"HDRI Controls — {name_suffix}" if name_suffix else "HDRI Controls"
    ng = bpy.data.node_groups.new(ng_name, 'ShaderNodeTree')
    ng.use_fake_user = True

    iface = ng.interface
    iface.new_socket(name="Output", in_out='OUTPUT', socket_type='NodeSocketShader')
    strength = iface.new_socket(name="Strength", in_out='INPUT', socket_type='NodeSocketFloat')
    hue = iface.new_socket(name="Hue", in_out='INPUT', socket_type='NodeSocketFloat')
    sat = iface.new_socket(name="Saturation", in_out='INPUT', socket_type='NodeSocketFloat')
    val = iface.new_socket(name="Value", in_out='INPUT', socket_type='NodeSocketFloat')
    rot = iface.new_socket(name="Rotation", in_out='INPUT', socket_type='NodeSocketVector')

    strength.default_value = 1.0; strength.min_value = 0.0; strength.max_value = 100.0; strength.subtype = 'FACTOR'
    hue.default_value = 0.5; hue.min_value = 0.0; hue.max_value = 1.0; hue.subtype = 'FACTOR'
    sat.default_value = 1.0; sat.min_value = 0.0; sat.max_value = 2.0; sat.subtype = 'FACTOR'
    val.default_value = 1.0; val.min_value = 0.0; val.max_value = 2.0; val.subtype = 'FACTOR'
    rot.default_value = (0.0, 0.0, 0.0); rot.subtype = 'EULER'

    nodes = ng.nodes
    links = ng.links

    tex_coord = nodes.new('ShaderNodeTexCoord')
    tex_coord.location = (-1000, 0)
    mapping = nodes.new('ShaderNodeMapping')
    mapping.location = (-800, 0)
    tex = nodes.new('ShaderNodeTexEnvironment')
    tex.name = "HDRI Texture"
    tex.location = (-600, 0)
    tex.interpolation = 'Smart'
    tex.projection = 'EQUIRECTANGULAR'
    hsv = nodes.new('ShaderNodeHueSaturation')
    hsv.location = (-400, 0)
    bg = nodes.new('ShaderNodeBackground')
    bg.location = (-200, 0)
    group_in = nodes.new('NodeGroupInput')
    group_in.location = (-1200, 0)
    group_out = nodes.new('NodeGroupOutput')
    group_out.location = (0, 0)

    links.new(group_in.outputs['Rotation'], mapping.inputs['Rotation'])
    links.new(tex_coord.outputs['Generated'], mapping.inputs['Vector'])
    links.new(mapping.outputs['Vector'], tex.inputs['Vector'])
    links.new(tex.outputs['Color'], hsv.inputs['Color'])
    links.new(hsv.outputs['Color'], bg.inputs['Color'])
    links.new(group_in.outputs['Strength'], bg.inputs['Strength'])
    links.new(group_in.outputs['Hue'], hsv.inputs['Hue'])
    links.new(group_in.outputs['Saturation'], hsv.inputs['Saturation'])
    links.new(group_in.outputs['Value'], hsv.inputs['Value'])
    links.new(bg.outputs['Background'], group_out.inputs['Output'])
    hsv.inputs['Fac'].default_value = 1.0

    return ng


def generate_panoramic_preview(world, filepath):
    try:
        img = bpy.data.images.load(filepath, check_existing=True)
        width, height = img.size
        if width < 512 or height < 128: return

        target_w, target_h = 512, 256
        crop_w = min(width, target_w)
        crop_h = min(height, int(crop_w * 0.5))
        y_start = (height - crop_h) // 2
        x_start = (width - crop_w) // 2

        preview_name = f"preview_{world.name}"
        if preview_name in bpy.data.images:
            bpy.data.images.remove(bpy.data.images[preview_name])

        preview_img = bpy.data.images.new(preview_name, target_w, target_h, alpha=False, float_buffer=True)
        pixels = [0.0] * (target_w * target_h * 4)
        src = list(img.pixels)

        for y in range(crop_h):
            for x in range(crop_w):
                sx = x_start + x
                sy = y_start + y
                dx = x + (target_w - crop_w) // 2
                dy = y + (target_h - crop_h) // 2
                if dx >= target_w or dy >= target_h: continue
                si = (sy * width + sx) * 4
                di = (dy * target_w + dx) * 4
                for c in range(4):
                    pixels[di + c] = src[si + c]

        preview_img.pixels.foreach_set(pixels)
        preview_img.update()

        temp_path = bpy.app.tempdir + f"/hdri_preview_{world.name}.png"
        preview_img.file_format = 'PNG'
        preview_img.save(filepath=temp_path)

        world.asset_mark()
        with bpy.context.temp_override(id=world):
            bpy.ops.ed.lib_id_load_custom_preview(filepath=temp_path)
        if os.path.exists(temp_path):
            os.remove(temp_path)
    except Exception as e:
        print(f"HDRI Helper: Preview failed: {e}")


def rebuild_world_nodes(world):
    if not world or not world.use_nodes: return
    tree = world.node_tree
    tree.nodes.clear()

    output = tree.nodes.new('ShaderNodeOutputWorld')
    output.location = (600, 0)

    main_group = tree.nodes.new('ShaderNodeGroup')
    main_group.node_tree = world.hdri_props.main_node_group
    main_group.location = (-200, 200)
    main_group["hdri_main"] = True

    if world.hdri_props.use_background and world.hdri_props.background_hdri:
        bg_group = tree.nodes.new('ShaderNodeGroup')
        bg_group.node_tree = world.hdri_props.background_hdri.hdri_props.main_node_group
        bg_group.location = (-200, -200)
        bg_group["hdri_background"] = True

        lp = tree.nodes.new('ShaderNodeLightPath')
        mix = tree.nodes.new('ShaderNodeMixShader')
        lp.location = (200, 0)
        mix.location = (400, 0)

        tree.links.new(main_group.outputs[0], mix.inputs[1])
        tree.links.new(bg_group.outputs[0], mix.inputs[2])
        tree.links.new(lp.outputs['Is Camera Ray'], mix.inputs[0])
        tree.links.new(mix.outputs[0], output.inputs[0])
    else:
        tree.links.new(main_group.outputs[0], output.inputs[0])


class WORLD_OT_import_hdri_as_asset(Operator):
    bl_idname = "world.import_hdri_as_asset"
    bl_label = "Add World Assets"
    bl_options = {'REGISTER', 'UNDO'}

    files: bpy.props.CollectionProperty(type=bpy.types.OperatorFileListElement)
    directory: StringProperty(subtype='DIR_PATH')

    def execute(self, context):
        if not self.files:
            self.report({'WARNING'}, "No files selected")
            return {'CANCELLED'}

        valid_files = []
        for f in self.files:
            if f.name.lower().endswith(('.exr', '.hdr')):
                path = os.path.join(self.directory, f.name)
                if not any(getattr(w, "hdri_props", None) and w.hdri_props.hdri_path == path for w in bpy.data.worlds):
                    valid_files.append(path)

        total = len(valid_files)
        if total == 0:
            self.report({'INFO'}, "No new HDRIs")
            return {'CANCELLED'}

        # PROGRESS BAR + WAIT CURSOR
        wm = context.window_manager
        wm.progress_begin(0, total)
        context.window.cursor_set("WAIT")

        for i, path in enumerate(valid_files):
            self.create_hdri_world(path)
            wm.progress_update(i + 1)

        wm.progress_end()
        context.window.cursor_set("DEFAULT")
        self.report({'INFO'}, f"Imported {total} HDRI(s)")
        return {'FINISHED'}

    def invoke(self, context, event):
        context.window_manager.fileselect_add(self)
        return {'RUNNING_MODAL'}

    def create_hdri_world(self, filepath):
        clean_name = title_case_hdri_name(filepath)
        world = bpy.data.worlds.new(clean_name)
        world.use_nodes = True

        ng = create_hdri_node_group(clean_name)
        world.hdri_props.main_node_group = ng

        tree = world.node_tree
        tree.nodes.clear()
        output = tree.nodes.new('ShaderNodeOutputWorld')
        output.location = (300, 0)
        group_node = tree.nodes.new('ShaderNodeGroup')
        group_node.node_tree = ng
        group_node["hdri_main"] = True
        tree.links.new(group_node.outputs[0], output.inputs[0])

        img = bpy.data.images.load(filepath, check_existing=True)
        ng.nodes["HDRI Texture"].image = img
        world.hdri_props.hdri_path = filepath
        generate_panoramic_preview(world, filepath)

        world.asset_mark()
        world.asset_data.author = "HDRI Helper"
        world.asset_data.description = f"HDRI: {os.path.basename(filepath)}"
        world.asset_data.tags.new("HDRI")
        world.asset_data.tags.new("World")


class WORLD_PT_hdri_helper(Panel):
    bl_label = "HDRI Helper"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "world"

    def draw(self, context):
        layout = self.layout
        col = layout.column(align=True)
        col.scale_y = 1.5
        col.operator("world.import_hdri_as_asset", text="Add World Assets", icon='WORLD')

        if context.scene.world and hasattr(context.scene.world, "hdri_props"):
            world = context.scene.world
            props = world.hdri_props

            box = layout.box()
            box.label(text=f"Lighting HDRI: {world.name}", icon='WORLD')
            main_group = next((n for n in world.node_tree.nodes if n.get("hdri_main")), None)
            if main_group:
                for inp in main_group.inputs:
                    if inp.name != "Output":
                        box.prop(inp, "default_value", text=inp.name)

            layout.prop(props, "use_background")

            if props.use_background:
                box = layout.box()
                box.label(text="Background HDRI", icon='WORLD')
                row = box.row()
                row.prop(props, "background_hdri", text="")
                row.operator("world.import_hdri_as_asset", text="", icon='FILE_FOLDER')

                if props.background_hdri:
                    bg_group = next((n for n in world.node_tree.nodes if n.get("hdri_background")), None)
                    if bg_group:
                        for inp in bg_group.inputs:
                            if inp.name != "Output":
                                box.prop(inp, "default_value", text=inp.name)


classes = (
    HDRIWorldProps,
    WORLD_OT_import_hdri_as_asset,
    WORLD_PT_hdri_helper,
)

def register():
    for c in classes:
        bpy.utils.register_class(c)
    bpy.types.World.hdri_props = PointerProperty(type=HDRIWorldProps)
    register_handler()

def unregister():
    for c in reversed(classes):
        bpy.utils.unregister_class(c)
    del bpy.types.World.hdri_props
    unregister_handler()

if __name__ == "__main__":
    register()