#!/usr/bin/env python3
"""
Check dependencies and node setup without creating Qt widgets.
"""

import sys
import os

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

def check_dependencies():
    """Check if required dependencies are available."""
    print("Checking dependencies...")
    
    dependencies = [
        ('PyQt5', 'PyQt5.QtWidgets'),
        ('NodeGraphQt', 'NodeGraphQt'),
    ]
    
    results = {}
    
    for dep_name, import_path in dependencies:
        try:
            __import__(import_path)
            print(f"✓ {dep_name} is available")
            results[dep_name] = True
        except ImportError as e:
            print(f"✗ {dep_name} is missing: {e}")
            results[dep_name] = False
    
    return results

def check_node_classes():
    """Check if node classes are properly defined."""
    print("\nChecking node classes...")
    
    try:
        from cluster4npu_ui.core.nodes.simple_input_node import (
            SimpleInputNode, SimpleModelNode, SimplePreprocessNode,
            SimplePostprocessNode, SimpleOutputNode, SIMPLE_NODE_TYPES
        )
        
        print("✓ Simple nodes imported successfully")
        
        # Check node identifiers
        for node_name, node_class in SIMPLE_NODE_TYPES.items():
            identifier = getattr(node_class, '__identifier__', 'MISSING')
            node_display_name = getattr(node_class, 'NODE_NAME', 'MISSING')
            print(f"  {node_name}: {identifier} ({node_display_name})")
        
        return True
        
    except Exception as e:
        print(f"✗ Failed to import nodes: {e}")
        import traceback
        traceback.print_exc()
        return False

def check_nodegraph_import():
    """Check if NodeGraphQt can be imported and used."""
    print("\nChecking NodeGraphQt functionality...")
    
    try:
        from NodeGraphQt import NodeGraph, BaseNode
        print("✓ NodeGraphQt classes imported successfully")
        
        # Check if we can create a basic node class
        class TestNode(BaseNode):
            __identifier__ = 'test.node'
            NODE_NAME = 'Test Node'
        
        print("✓ Can create BaseNode subclass")
        return True
        
    except ImportError as e:
        print(f"✗ NodeGraphQt import failed: {e}")
        return False
    except Exception as e:
        print(f"✗ NodeGraphQt functionality test failed: {e}")
        return False

def provide_solution():
    """Provide solution steps."""
    print("\n" + "=" * 50)
    print("SOLUTION STEPS")
    print("=" * 50)
    
    print("\n1. Install missing dependencies:")
    print("   pip install NodeGraphQt")
    print("   pip install PyQt5")
    
    print("\n2. Verify installation:")
    print("   python -c \"import NodeGraphQt; print('NodeGraphQt OK')\"")
    print("   python -c \"import PyQt5; print('PyQt5 OK')\"")
    
    print("\n3. The node registration issue is likely due to:")
    print("   - Missing NodeGraphQt dependency")
    print("   - Incorrect node identifier format")
    print("   - Node class not properly inheriting from BaseNode")
    
    print("\n4. After installing dependencies, restart the application")
    print("   The 'Can't find node' error should be resolved.")

def main():
    """Run all checks."""
    print("CLUSTER4NPU NODE DEPENDENCY CHECK")
    print("=" * 50)
    
    # Check dependencies
    deps = check_dependencies()
    
    # Check node classes
    nodes_ok = check_node_classes()
    
    # Check NodeGraphQt functionality
    nodegraph_ok = check_nodegraph_import()
    
    print("\n" + "=" * 50)
    print("SUMMARY")
    print("=" * 50)
    
    if deps.get('NodeGraphQt', False) and deps.get('PyQt5', False) and nodes_ok and nodegraph_ok:
        print("✓ ALL CHECKS PASSED")
        print("The node registration should work correctly.")
        print("If you're still getting errors, try restarting the application.")
    else:
        print("✗ SOME CHECKS FAILED")
        provide_solution()

if __name__ == "__main__":
    main()