#!/usr/bin/env python3
"""
Example script demonstrating Kneron device auto-detection functionality.
This script shows how to scan for devices and connect to them automatically.
"""

import sys
import os

# Add the core functions path to sys.path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'core', 'functions'))

def example_device_scan():
    """
    Example 1: Scan for available devices without connecting
    """
    print("=== Example 1: Device Scanning ===")
    
    try:
        from Multidongle import MultiDongle
        
        # Scan for available devices
        devices = MultiDongle.scan_devices()
        
        if not devices:
            print("No Kneron devices found")
            return
        
        print(f"Found {len(devices)} device(s):")
        for i, device in enumerate(devices):
            desc = device['device_descriptor']
            product_id = desc.get('product_id', 'Unknown') if isinstance(desc, dict) else 'Unknown'
            print(f"  [{i+1}] Port ID: {device['port_id']}, Series: {device['series']}, Product ID: {product_id}")
            
    except Exception as e:
        print(f"Error during device scan: {str(e)}")

def example_auto_connect():
    """
    Example 2: Auto-connect to all available devices
    """
    print("\n=== Example 2: Auto-Connect to Devices ===")
    
    try:
        from Multidongle import MultiDongle
        
        # Connect to all available devices automatically
        device_group, connected_devices = MultiDongle.connect_auto_detected_devices()
        
        print(f"Successfully connected to {len(connected_devices)} device(s):")
        for i, device in enumerate(connected_devices):
            desc = device['device_descriptor']
            product_id = desc.get('product_id', 'Unknown') if isinstance(desc, dict) else 'Unknown'
            print(f"  [{i+1}] Port ID: {device['port_id']}, Series: {device['series']}, Product ID: {product_id}")
        
        # Disconnect devices
        import kp
        kp.core.disconnect_devices(device_group=device_group)
        print("Devices disconnected")
        
    except Exception as e:
        print(f"Error during auto-connect: {str(e)}")

def example_multidongle_with_auto_detect():
    """
    Example 3: Use MultiDongle with auto-detection
    """
    print("\n=== Example 3: MultiDongle with Auto-Detection ===")
    
    try:
        from Multidongle import MultiDongle
        
        # Create MultiDongle instance with auto-detection
        # Note: You'll need to provide firmware and model paths for full initialization
        multidongle = MultiDongle(
            auto_detect=True,
            scpu_fw_path="path/to/fw_scpu.bin",  # Update with actual path
            ncpu_fw_path="path/to/fw_ncpu.bin",  # Update with actual path  
            model_path="path/to/model.nef",      # Update with actual path
            upload_fw=False  # Set to True if you want to upload firmware
        )
        
        # Print device information
        multidongle.print_device_info()
        
        # Get device info programmatically
        device_info = multidongle.get_device_info()
        
        print("\nDevice details:")
        for device in device_info:
            print(f"  Port ID: {device['port_id']}, Series: {device['series']}")
        
    except Exception as e:
        print(f"Error during MultiDongle auto-detection: {str(e)}")

def example_connect_specific_count():
    """
    Example 4: Connect to specific number of devices
    """
    print("\n=== Example 4: Connect to Specific Number of Devices ===")
    
    try:
        from Multidongle import MultiDongle
        
        # Connect to only 2 devices (or all available if less than 2)
        device_group, connected_devices = MultiDongle.connect_auto_detected_devices(device_count=2)
        
        print(f"Connected to {len(connected_devices)} device(s):")
        for i, device in enumerate(connected_devices):
            print(f"  [{i+1}] Port ID: {device['port_id']}, Series: {device['series']}")
        
        # Disconnect devices
        import kp
        kp.core.disconnect_devices(device_group=device_group)
        print("Devices disconnected")
        
    except Exception as e:
        print(f"Error during specific count connect: {str(e)}")

if __name__ == "__main__":
    print("Kneron Device Auto-Detection Examples")
    print("=" * 50)
    
    # Run examples
    example_device_scan()
    example_auto_connect()
    example_multidongle_with_auto_detect()
    example_connect_specific_count()
    
    print("\n" + "=" * 50)
    print("Examples completed!")
    print("\nUsage Notes:")
    print("- Make sure Kneron devices are connected via USB")
    print("- Update firmware and model paths in example 3")
    print("- The examples require the Kneron SDK to be properly installed")