bl_info = {
    "name": "ThemeFaves",
    "author": "Jonathan & Gidget",
    "version": (1, 5, 40),
    "blender": (4, 3, 0),
    "location": "Preferences > Add-ons > ThemeFaves",
    "description": "Manage and lock favorite theme colors with a user-friendly list",
    "category": "Interface",
}

import bpy
import os
import json
from bpy.types import AddonPreferences, PropertyGroup, Operator
from bpy.props import StringProperty, FloatVectorProperty, BoolProperty, CollectionProperty, IntProperty, EnumProperty


THEME_COLOR_ITEMS = [
    ("view_3d.object_active", "Active Object", "Active object color"),
    ("view_3d.editmesh_active", "Active Vertex, Edge, Face", "The active color for vertex, edge, or face in edit mode"),
    ("user_interface.axis_x", "Axis X", "X-axis color (view/gizmos)"),
    ("user_interface.axis_y", "Axis Y", "Y-axis color (view/gizmos)"),
    ("user_interface.axis_z", "Axis Z", "Z-axis color (view/gizmos)"),
    ("view_3d.camera", "Camera", "Camera color"),
    ("view_3d.edge_bevel", "Edge Bevel", "Edge bevel color"),
    ("view_3d.edge_crease", "Edge Crease", "Edge crease color"),
    ("view_3d.edge_seam", "Edge Seam", "Edge seam color"),
    ("view_3d.edge_sharp", "Edge Sharp", "Sharp edge color"),
    ("view_3d.empty", "Empty", "Empty color"),
    ("view_3d.face", "Face", "Face color in face mode"),
    ("view_3d.grid", "Grid", "Grid color"),
    ("view_3d.light", "Light", "Light color"),
    ("view_3d.edge_mode_select", "Selected Edge - Edge Mode", "Selected edge color in edge mode"),
    ("view_3d.edge_select", "Selected Edge - Vertex Mode", "Selected edge color in vertex mode"),
    ("view_3d.face_mode_select", "Selected Face - Face Mode", "Selected face color in face mode"),
    ("view_3d.face_select", "Selected Face - Vertex/Edge Mode", "Selected face color in edge or vertex mode"),
    ("view_3d.object_selected", "Selected Object", "Selected object"),
    ("view_3d.vertex_select", "Selected Vertex", "Selected vertex color"),
    ("view_3d.vertex", "Vertex", "Vertex color"),
    ("view_3d.wire", "Viewport Shading - Wireframe", "Viewport shading wireframe color"),
]


class ThemeColorItem(PropertyGroup):
    """Item in the theme color list."""
    path: EnumProperty(
        name="Theme Element",
        description="Select a theme element to control its color",
        items=THEME_COLOR_ITEMS
    )
    color: FloatVectorProperty(
        name="Color",
        subtype='COLOR',
        size=4,
        min=0.0,
        max=1.0,
        default=(0.0, 0.0, 0.0, 1.0),
        update=lambda self, context: enforce_color_update(self, context)
    )
    locked: BoolProperty(
        name="Lock",
        description="Lock this color to prevent changes",
        default=True
    )


def enforce_color_update(self, context):
    """Apply the color to the theme when changed and enforce all locked colors."""
    if self is None:  # Handle empty list gracefully
        print("ThemeFaves: No items to enforce, list is empty")
        return
    
    theme = bpy.context.preferences.themes[0]
    prefs = context.preferences.addons[__name__].preferences
    try:
        # Update the changed color
        attr = theme
        print(f"ThemeFaves: Accessing path {self.path} for update")
        for part in self.path.split('.'):
            print(f"ThemeFaves: Navigating to part {part}")
            attr = getattr(attr, part)
        current_color = tuple(attr)  # Get full color (3 or 4 components)
        print(f"ThemeFaves: Current theme color for {self.path} is {current_color}")
        if len(current_color) == 3:  # RGB-only (e.g., axes, object outlines, grid, empty, edges, faces)
            if current_color != self.color[0:3]:  # Compare only RGB
                rgb_color = (self.color[0], self.color[1], self.color[2])  # Use RGB, ignore alpha
                print(f"ThemeFaves: RGB-only path {self.path}, clamping alpha to 1.0, setting to {rgb_color}")
                attr[0:3] = rgb_color  # Set RGB only, ignore alpha
                print(f"ThemeFaves: Set RGB {self.path} to {rgb_color}")
        else:  # RGBA (e.g., camera, light)
            if current_color != self.color:
                print(f"ThemeFaves: RGBA path {self.path}, preserving alpha, setting to {self.color}")
                attr[0:4] = self.color  # Set full RGBA, including alpha
                print(f"ThemeFaves: Set RGBA {self.path} to {self.color}")
        
        # Enforce all locked colors (theme might’ve changed)
        for item in prefs.theme_colors:
            if item.locked:
                attr = theme
                print(f"ThemeFaves: Enforcing path {item.path}")
                for part in item.path.split('.'):
                    print(f"ThemeFaves: Navigating to part {part}")
                    attr = getattr(attr, part)
                current_color = tuple(attr)
                print(f"ThemeFaves: Current theme color for {item.path} is {current_color}")
                if len(current_color) == 3:  # RGB-only
                    if current_color != item.color[0:3]:  # Compare only RGB
                        rgb_color = (item.color[0], item.color[1], item.color[2])  # Use RGB, ignore alpha
                        print(f"ThemeFaves: RGB-only path {item.path}, clamping alpha to 1.0, enforcing to {rgb_color}")
                        attr[0:3] = rgb_color  # Set RGB only, ignore alpha
                        print(f"ThemeFaves: Enforced RGB {item.path} to {rgb_color}")
                else:  # RGBA
                    if current_color != item.color:
                        print(f"ThemeFaves: RGBA path {item.path}, preserving alpha, enforcing to {item.color}")
                        attr[0:4] = item.color  # Set full RGBA, including alpha
                        print(f"ThemeFaves: Enforced RGBA {item.path} to {item.color}")
        
        save_faves(context)  # Save on change
        for area in bpy.context.screen.areas:
            if area.type in {'VIEW_3D', 'NODE_EDITOR'}:
                area.tag_redraw()
    except AttributeError as e:
        print(f"ThemeFaves: Invalid theme length: {self.path}, error: {e}")


class ThemeFavesPreferences(AddonPreferences):
    """Preferences for ThemeFaves addon."""
    bl_idname = __name__

    theme_colors: CollectionProperty(type=ThemeColorItem)
    active_index: IntProperty(default=-1)
    faves_file: StringProperty(
        name="Faves File",
        description="Path to the themefaves.json file",
        default=""
    )

    def draw(self, context):
        layout = self.layout
        has_file = bool(self.faves_file)

        if not has_file:
            row = layout.row()
            row.alert = True  # Red text
            row.label(text="Set a Faves File below to start!")

        # "Element" is our top heading—Blender adds "Preferences" above, can't remove it directly
        row = layout.row()
        row.label(text="Element")
        row.label(text="")

        row = layout.row()
        row.enabled = has_file  # Disable list unless file set
        row.template_list("THEMEFAVES_UL_colors", "", self, "theme_colors", self, "active_index", rows=4)

        col = row.column(align=True)
        col.operator("themefaves.add_theme_color", text="", icon='ADD')
        col.operator("themefaves.remove_theme_color", text="", icon='REMOVE')
        col.operator("themefaves.move_up", text="", icon='TRIA_UP')
        col.operator("themefaves.move_down", text="", icon='TRIA_DOWN')

        if self.theme_colors and 0 <= self.active_index < len(self.theme_colors):
            item = self.theme_colors[self.active_index]
            # Edit row (lock only, tight against list)
            row = layout.row(align=True)
            row.enabled = has_file  # Disable controls unless file set
            row.alignment = 'LEFT'
            sub = row.row(align=True)
            sub.alignment = 'RIGHT'
            sub.prop(item, "locked", text="", emboss=False)
            # Color picker row
            row = layout.row(align=True)
            row.enabled = has_file
            row.alignment = 'LEFT'
            sub = row.row(align=True)
            sub.scale_x = 2.0  # ~100px for "Color:"
            sub.label(text="Color:")
            sub = row.row(align=True)
            sub.scale_x = 2.0  # ~100px for swatch
            sub.prop(item, "color", text="")
            sub = row.row(align=True)
            sub.scale_x = 4.0  # ~200px for status
            sub.label(text="Locked and enforced!", icon='LOCKED')
            # Description row (full width, below edit)
            row = layout.row(align=True)
            row.enabled = has_file
            row.alignment = 'LEFT'
            description = next(x[2] for x in THEME_COLOR_ITEMS if x[0] == item.path)
            row.label(text=description)
        else:
            row = layout.row()
            row.enabled = has_file  # Disable label unless file set
            row.label(text="Add an item to start editing colors")

        # Refresh After Theme Change always visible, disabled if no file
        row = layout.row(align=True)
        row.enabled = has_file
        row.operator("themefaves.refresh_after_theme_change", text="Refresh After Theme Change")

        row = layout.row(align=True)
        sub = row.row(align=True)
        sub.scale_x = 2.0  # ~100px for label
        sub.label(text="Faves File:")
        sub = row.row(align=True)
        sub.scale_x = 4.0  # Wider path field
        sub.alert = not has_file  # Red if unset
        sub.label(text=self.faves_file if self.faves_file else "Not set")
        sub = row.row(align=True)
        sub.scale_x = 1.0  # ~50px, wider for folder icon spacing
        sub.operator("themefaves.set_faves_file", text="", icon='FILEBROWSER')


class THEMEFAVES_UL_colors(bpy.types.UIList):
    """Custom UI list for theme colors."""
    def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
        row = layout.row(align=True)
        # Column 1: Name, fixed width, left-justified
        sub = row.row(align=True)
        sub.alignment = 'LEFT'
        sub.scale_x = 5.0  # ~250px, fixed width for names
        name = next(x[1] for x in THEME_COLOR_ITEMS if x[0] == item.path)
        sub.label(text=name)
        # Column 2: Lock toggle, right-justified (no description here)
        sub = row.row(align=True)
        sub.alignment = 'RIGHT'
        sub.prop(item, "locked", text="", emboss=False)


class THEMEFAVES_OT_add_theme_color(bpy.types.Operator):
    """Add a new theme color to the list."""
    bl_idname = "themefaves.add_theme_color"
    bl_label = "Add Theme Color"
    
    new_path: EnumProperty(
        name="Theme Element",
        description="Select a theme element to add",
        items=THEME_COLOR_ITEMS
    )

    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self)

    def draw(self, context):
        layout = self.layout
        layout.prop(self, "new_path")

    def execute(self, context):
        prefs = context.preferences.addons[__name__].preferences
        if not prefs.faves_file:
            self.report({'ERROR'}, "Please set a Faves File first!")
            return {'CANCELLED'}
        
        for item in prefs.theme_colors:
            if item.path == self.new_path:
                friendly_name = next(x[1] for x in THEME_COLOR_ITEMS if x[0] == self.new_path)
                self.report({'WARNING'}, f"'{friendly_name}' is already in the list!")
                return {'CANCELLED'}
        
        item = prefs.theme_colors.add()
        item.path = self.new_path
        item.locked = True
        theme = bpy.context.preferences.themes[0]
        try:
            attr = theme
            for part in self.new_path.split('.'):
                attr = getattr(attr, part)
            item.color = tuple(attr[0:4]) if len(attr) == 4 else tuple(attr[0:3]) + (1.0,)  # Fetch RGBA or RGB + 1.0
            print(f"ThemeFaves: Initial color for {self.new_path} is {item.color}")
        except AttributeError:
            print(f"ThemeFaves: Couldn’t fetch current color for {self.new_path}")
        prefs.active_index = len(prefs.theme_colors) - 1
        enforce_color_update(item, context)
        return {'FINISHED'}


class THEMEFAVES_OT_remove_theme_color(bpy.types.Operator):
    """Remove the selected theme color from the list."""
    bl_idname = "themefaves.remove_theme_color"
    bl_label = "Remove Theme Color"

    def execute(self, context):
        prefs = context.preferences.addons[__name__].preferences
        if not prefs.faves_file:
            self.report({'ERROR'}, "Please set a Faves File first!")
            return {'CANCELLED'}
        if prefs.theme_colors and 0 <= prefs.active_index < len(prefs.theme_colors):
            prefs.theme_colors.remove(prefs.active_index)
            if not prefs.theme_colors:  # If list is now empty
                prefs.active_index = -1
            else:
                prefs.active_index = min(prefs.active_index, len(prefs.theme_colors) - 1)
            enforce_color_update(prefs.theme_colors[prefs.active_index] if prefs.theme_colors else None, context)
        return {'FINISHED'}


class THEMEFAVES_OT_move_up(bpy.types.Operator):
    """Move the selected theme color up in the list."""
    bl_idname = "themefaves.move_up"
    bl_label = "Move Up"

    def execute(self, context):
        prefs = context.preferences.addons[__name__].preferences
        if not prefs.faves_file:
            self.report({'ERROR'}, "Please set a Faves File first!")
            return {'CANCELLED'}
        if prefs.active_index > 0:  # Not at top
            prefs.theme_colors.move(prefs.active_index, prefs.active_index - 1)
            prefs.active_index -= 1
            save_faves(context)  # Save reordered list
        return {'FINISHED'}


class THEMEFAVES_OT_move_down(bpy.types.Operator):
    """Move the selected theme color down in the list."""
    bl_idname = "themefaves.move_down"
    bl_label = "Move Down"

    def execute(self, context):
        prefs = context.preferences.addons[__name__].preferences
        if not prefs.faves_file:
            self.report({'ERROR'}, "Please set a Faves File first!")
            return {'CANCELLED'}
        if 0 <= prefs.active_index < len(prefs.theme_colors) - 1:  # Not at bottom
            prefs.theme_colors.move(prefs.active_index, prefs.active_index + 1)
            prefs.active_index += 1
            save_faves(context)  # Save reordered list
        return {'FINISHED'}


class THEMEFAVES_OT_refresh_after_theme_change(Operator):
    """Manually refresh all locked colors after a theme change."""
    bl_idname = "themefaves.refresh_after_theme_change"
    bl_label = "Refresh After Theme Change"

    def execute(self, context):
        prefs = context.preferences.addons[__name__].preferences
        if not prefs.faves_file:
            self.report({'ERROR'}, "Please set a Faves File first!")
            return {'CANCELLED'}
        theme = bpy.context.preferences.themes[0]
        for item in prefs.theme_colors:
            if item.locked:
                try:
                    print(f"ThemeFaves: Refreshing {item.path}, locked: {item.locked}, current color: {item.color}")
                    attr = theme
                    for part in item.path.split('.'):
                        print(f"ThemeFaves: Navigating to part {part}")
                        attr = getattr(attr, part)
                    current_color = tuple(attr)  # Get full color
                    print(f"ThemeFaves: Theme color for {item.path} (before) is {current_color}")
                    if len(current_color) == 3:  # RGB-only (e.g., axes, object outlines, grid, empty, edges, faces)
                        if current_color != item.color[0:3]:  # Compare only RGB
                            print(f"ThemeFaves: Updating RGB {item.path} from {current_color} to {item.color[0:3]}")
                            attr[0:3] = item.color[0:3]  # Set RGB only, ignore alpha
                            for area in bpy.context.screen.areas:
                                if area.type in {'VIEW_3D', 'NODE_EDITOR'}:
                                    area.tag_redraw()
                    else:  # RGBA (e.g., camera, light)
                        if current_color != item.color:
                            print(f"ThemeFaves: Updating RGBA {item.path} from {current_color} to {item.color}")
                            attr[0:4] = item.color  # Set full RGBA, including alpha
                            for area in bpy.context.screen.areas:
                                if area.type in {'VIEW_3D', 'NODE_EDITOR'}:
                                    area.tag_redraw()
                    # Re-fetch to verify
                    current_color = tuple(getattr(theme, item.path.split('.')[-1]))
                    print(f"ThemeFaves: Refreshed {item.path} to {item.color}, theme now {current_color}")
                except AttributeError as e:
                    print(f"ThemeFaves: Error refreshing {item.path}: {e}")
        return {'FINISHED'}


class THEMEFAVES_OT_set_faves_file(bpy.types.Operator):
    """Set the folder for themefaves.json."""
    bl_idname = "themefaves.set_faves_file"
    bl_label = "Set Faves File Folder"
    
    directory: StringProperty(subtype='DIR_PATH')

    def invoke(self, context, event):
        context.window_manager.fileselect_add(self)
        return {'RUNNING_MODAL'}

    def execute(self, context):
        prefs = context.preferences.addons[__name__].preferences
        prefs.faves_file = os.path.join(self.directory, "themefaves.json")
        if os.path.exists(prefs.faves_file):
            try:
                with open(prefs.faves_file, 'r') as f:
                    data = json.load(f)
                prefs.theme_colors.clear()
                valid_paths = [item[0] for item in THEME_COLOR_ITEMS]
                for entry in data:
                    if "path" in entry and entry["path"] in valid_paths:
                        item = prefs.theme_colors.add()
                        item.path = entry["path"]
                        item.color = entry["color"]
                        item.locked = entry["locked"]
                    else:
                        print(f"ThemeFaves: Skipping invalid path {entry.get('path', 'None')} in JSON")
                if not prefs.theme_colors:  # If no valid items loaded
                    self.report({'WARNING'}, f"No valid items found in {prefs.faves_file}, starting fresh")
                    save_faves(context)  # Create fresh file
                else:
                    print(f"ThemeFaves: Loaded faves from {prefs.faves_file}")
                    # Enforce locked colors on load
                    enforce_locked_colors(context.scene)
            except (json.JSONDecodeError, KeyError) as e:
                self.report({'WARNING'}, f"Invalid themefaves.json at {prefs.faves_file}: {e}, starting fresh")
                save_faves(context)  # Create fresh file
        else:
            save_faves(context)  # Create new file
        return {'FINISHED'}


def save_faves(context):
    """Save theme_colors to themefaves.json."""
    prefs = context.preferences.addons[__name__].preferences
    if not prefs.faves_file:
        return
    data = [{"path": item.path, "color": list(item.color), "locked": item.locked} for item in prefs.theme_colors]
    try:
        with open(prefs.faves_file, 'w') as f:
            json.dump(data, f, indent=4)
        print(f"ThemeFaves: Saved faves to {prefs.faves_file}")
    except IOError:
        print(f"ThemeFaves: Failed to save faves to {prefs.faves_file}")


def enforce_locked_colors(scene):
    """Handler to enforce locked theme colors on file load."""
    if __name__ not in bpy.context.preferences.addons:
        return
    prefs = bpy.context.preferences.addons[__name__].preferences
    if not prefs.faves_file or not prefs.theme_colors:
        print("ThemeFaves: No faves file or items to enforce on load")
        return
    theme = bpy.context.preferences.themes[0]
    for item in prefs.theme_colors:
        if item.locked:
            try:
                print(f"ThemeFaves: Enforcing {item.path} on load, color: {item.color}")
                attr = theme
                for part in item.path.split('.'):
                    print(f"ThemeFaves: Navigating to part {part}")
                    attr = getattr(attr, part)
                current_color = tuple(attr)  # Get full color
                if len(current_color) == 3:  # RGB-only (e.g., axes, object outlines, grid, empty, edges, faces)
                    if current_color != item.color[0:3]:  # Compare only RGB
                        print(f"ThemeFaves: Enforcing RGB {item.path} to {item.color[0:3]}")
                        attr[0:3] = item.color[0:3]  # Set RGB only, ignore alpha
                        for area in bpy.context.screen.areas:
                            if area.type in {'VIEW_3D', 'NODE_EDITOR'}:
                                area.tag_redraw()
                else:  # RGBA (e.g., camera, light)
                    if current_color != item.color:
                        print(f"ThemeFaves: Enforcing RGBA {item.path} to {item.color}")
                        attr[0:4] = item.color  # Set full RGBA, including alpha
                        for area in bpy.context.screen.areas:
                            if area.type in {'VIEW_3D', 'NODE_EDITOR'}:
                                area.tag_redraw()
            except AttributeError as e:
                print(f"ThemeFaves: Error enforcing {item.path} on load: {e}")


# Dummy property for preview (unused now)
bpy.types.Scene.theme_faves_dummy = FloatVectorProperty(
    name="Dummy",
    subtype='COLOR',
    size=4,
    min=0.0,
    max=1.0,
    default=(0.0, 0.0, 0.0, 1.0)
)

# Registration
classes = [
    ThemeColorItem,
    ThemeFavesPreferences,
    THEMEFAVES_UL_colors,
    THEMEFAVES_OT_add_theme_color,
    THEMEFAVES_OT_remove_theme_color,
    THEMEFAVES_OT_move_up,
    THEMEFAVES_OT_move_down,
    THEMEFAVES_OT_refresh_after_theme_change,
    THEMEFAVES_OT_set_faves_file,
]

def register():
    for cls in classes:
        bpy.utils.register_class(cls)
    bpy.app.handlers.load_post.append(enforce_locked_colors)

def unregister():
    if enforce_locked_colors in bpy.app.handlers.load_post:
        bpy.app.handlers.load_post.remove(enforce_locked_colors)
    try:
        del bpy.types.Scene.theme_faves_dummy
    except AttributeError:
        pass
    for cls in classes:
        try:
            bpy.utils.unregister_class(cls)
        except RuntimeError:
            pass

if __name__ == "__main__":
    register()