#!/usr/bin/env python3
"""
Debug the node registration process to find the exact issue.
"""

import sys
import os

# Add the project root to Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from PyQt5.QtWidgets import QApplication

def debug_registration_detailed():
    """Debug the registration process in detail."""
    app = QApplication(sys.argv)
    
    try:
        from NodeGraphQt import NodeGraph
        from cluster4npu_ui.core.nodes.simple_input_node import SimpleInputNode
        
        print("Creating NodeGraph...")
        graph = NodeGraph()
        
        print(f"Node class: {SimpleInputNode}")
        print(f"Node identifier: {SimpleInputNode.__identifier__}")
        print(f"Node name: {SimpleInputNode.NODE_NAME}")
        
        # Check if the node class has required methods
        required_methods = ['__init__', 'add_input', 'add_output', 'set_color', 'create_property']
        for method in required_methods:
            if hasattr(SimpleInputNode, method):
                print(f"✓ Has method: {method}")
            else:
                print(f"✗ Missing method: {method}")
        
        print("\nAttempting registration...")
        try:
            graph.register_node(SimpleInputNode)
            print("✓ Registration successful")
        except Exception as e:
            print(f"✗ Registration failed: {e}")
            import traceback
            traceback.print_exc()
            return False
        
        print("\nChecking registered nodes...")
        try:
            # Different ways to check registered nodes
            if hasattr(graph, 'registered_nodes'):
                registered = graph.registered_nodes()
                print(f"Registered nodes (method 1): {registered}")
            
            if hasattr(graph, '_registered_nodes'):
                registered = graph._registered_nodes
                print(f"Registered nodes (method 2): {registered}")
                
            if hasattr(graph, 'node_factory'):
                factory = graph.node_factory
                print(f"Node factory: {factory}")
                if hasattr(factory, '_NodeFactory__nodes'):
                    nodes = factory._NodeFactory__nodes
                    print(f"Factory nodes: {list(nodes.keys())}")
                    
        except Exception as e:
            print(f"Error checking registered nodes: {e}")
        
        print("\nAttempting node creation...")
        try:
            node = graph.create_node('com.cluster.input_node')
            print(f"✓ Node created successfully: {node}")
            return True
        except Exception as e:
            print(f"✗ Node creation failed: {e}")
            
            # Try alternative identifiers
            alternatives = [
                'SimpleInputNode',
                'Input Node',
                'com.cluster.InputNode',
                'cluster.input_node'
            ]
            
            for alt_id in alternatives:
                try:
                    print(f"Trying alternative identifier: {alt_id}")
                    node = graph.create_node(alt_id)
                    print(f"✓ Success with identifier: {alt_id}")
                    return True
                except:
                    print(f"✗ Failed with: {alt_id}")
            
            return False
            
    except Exception as e:
        print(f"Debug failed: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        app.quit()

def main():
    """Run detailed debugging."""
    print("DETAILED NODE REGISTRATION DEBUG")
    print("=" * 50)
    
    success = debug_registration_detailed()
    
    print("\n" + "=" * 50)
    if success:
        print("DEBUG SUCCESSFUL - Node creation working")
    else:
        print("DEBUG FAILED - Need to fix registration")

if __name__ == "__main__":
    main()