bl_info = {
    "name": "Overlapping Objects Detector",
    "author": "Grok + Jonathan",
    "version": (1, 2),
    "blender": (5, 2, 0),
    "location": "Sidebar (N) > Object > Overlapping Objects",
    "description": "Detect and manage objects with exact identical transforms in the active object's collection.",
    "category": "Object",
}

import bpy
from collections import defaultdict

class OVERLAP_OT_detect(bpy.types.Operator):
    """Detect objects with exact overlapping transforms"""
    bl_idname = "object.detect_overlaps"
    bl_label = "Detect Overlaps"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        coll = None
        if context.active_object and context.active_object.users_collection:
            coll = context.active_object.users_collection[0]
        else:
            coll = context.collection

        if not coll:
            self.report({'WARNING'}, "No collection found")
            return {'CANCELLED'}

        context.scene.overlap_current_collection = coll.name

        groups = defaultdict(list)
        for obj in coll.objects:
            if obj.type != 'MESH':
                continue
            matrix_key = tuple(round(v, 8) for row in obj.matrix_world for v in row)
            groups[matrix_key].append(obj)

        duplicates = {k: objs for k, objs in groups.items() if len(objs) > 1}

        if not duplicates:
            self.report({'INFO'}, f"No exact overlaps in collection: {coll.name}")
            context.scene.overlap_groups.clear()
            return {'FINISHED'}

        context.scene.overlap_groups.clear()
        for key, objs in duplicates.items():
            group = context.scene.overlap_groups.add()
            sorted_objs = sorted(objs, key=lambda o: o.name)
            group.original = sorted_objs[0].name
            for o in sorted_objs[1:]:
                item = group.duplicates.add()
                item.name = o.name

        self.report({'INFO'}, f"Found {len(duplicates)} overlap group(s) in {coll.name}")
        return {'FINISHED'}


class OVERLAP_OT_cleanup(bpy.types.Operator):
    """Move newer duplicates to OVERLAPS collection"""
    bl_idname = "object.cleanup_overlaps"
    bl_label = "Cleanup: Move Newer to OVERLAPS"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        coll = None
        if context.active_object and context.active_object.users_collection:
            coll = context.active_object.users_collection[0]
        else:
            coll = context.collection

        if not coll:
            self.report({'WARNING'}, "No collection found")
            return {'CANCELLED'}

        overlaps_coll = bpy.data.collections.get("OVERLAPS")
        if not overlaps_coll:
            overlaps_coll = bpy.data.collections.new("OVERLAPS")
            bpy.context.scene.collection.children.link(overlaps_coll)

        moved = 0
        for group in context.scene.overlap_groups:
            for item in group.duplicates:
                dup = bpy.data.objects.get(item.name)
                if dup and dup.name in [o.name for o in coll.objects]:
                    coll.objects.unlink(dup)
                    overlaps_coll.objects.link(dup)
                    moved += 1

        self.report({'INFO'}, f"Moved {moved} newer duplicates to OVERLAPS")
        return {'FINISHED'}


class OVERLAP_OT_select_duplicates(bpy.types.Operator):
    """Select only the duplicate (newer) objects"""
    bl_idname = "object.select_overlaps_duplicates"
    bl_label = "Select Duplicates Only"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        bpy.ops.object.select_all(action='DESELECT')
        count = 0
        for group in context.scene.overlap_groups:
            for item in group.duplicates:
                obj = bpy.data.objects.get(item.name)
                if obj:
                    obj.select_set(True)
                    count += 1
        self.report({'INFO'}, f"Selected {count} duplicate objects (originals left unselected)")
        return {'FINISHED'}


class OVERLAP_PT_panel(bpy.types.Panel):
    bl_label = "Overlapping Objects"
    bl_idname = "OVERLAP_PT_panel"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_category = "Object"

    def draw(self, context):
        layout = self.layout
        scene = context.scene

        layout.operator("object.detect_overlaps", icon='VIEWZOOM')

        if scene.get("overlap_current_collection"):
            layout.label(text=f"Collection: {scene.overlap_current_collection}", icon='OUTLINER_COLLECTION')

        if scene.overlap_groups:
            # Action buttons FIRST
            layout.label(text=f"Found {len(scene.overlap_groups)} group(s):", icon='ERROR')
            row = layout.row(align=True)
            row.operator("object.select_overlaps_duplicates", icon='SELECT_SET')
            row.operator("object.cleanup_overlaps", icon='TRASH')

            # Then the list
            for group in scene.overlap_groups:
                box = layout.box()
                box.label(text=f"Keep: {group.original}")
                for dup in group.duplicates:
                    box.label(text=f"   → {dup.name}")
        else:
            layout.label(text="No overlaps detected yet.")


# Properties
class OverlapGroup(bpy.types.PropertyGroup):
    original: bpy.props.StringProperty()
    duplicates: bpy.props.CollectionProperty(type=bpy.types.PropertyGroup)

class OverlapDuplicateItem(bpy.types.PropertyGroup):
    name: bpy.props.StringProperty()


def register():
    bpy.utils.register_class(OverlapDuplicateItem)
    bpy.utils.register_class(OverlapGroup)
    bpy.utils.register_class(OVERLAP_OT_detect)
    bpy.utils.register_class(OVERLAP_OT_cleanup)
    bpy.utils.register_class(OVERLAP_OT_select_duplicates)
    bpy.utils.register_class(OVERLAP_PT_panel)

    bpy.types.Scene.overlap_groups = bpy.props.CollectionProperty(type=OverlapGroup)
    bpy.types.Scene.overlap_current_collection = bpy.props.StringProperty()


def unregister():
    del bpy.types.Scene.overlap_current_collection
    del bpy.types.Scene.overlap_groups
    bpy.utils.unregister_class(OVERLAP_PT_panel)
    bpy.utils.unregister_class(OVERLAP_OT_select_duplicates)
    bpy.utils.unregister_class(OVERLAP_OT_cleanup)
    bpy.utils.unregister_class(OVERLAP_OT_detect)
    bpy.utils.unregister_class(OverlapGroup)
    bpy.utils.unregister_class(OverlapDuplicateItem)


if __name__ == "__main__":
    register()