#!/usr/bin/env python3
"""
Test script for USB card reader functionality
"""

import evdev
from evdev import InputDevice, categorize, ecodes
import time

def list_input_devices():
    """List all available input devices"""
    print("\n=== Available Input Devices ===")
    devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
    
    # Exclusion keywords that help identify non-card-reader devices
    exclusion_keywords = [
        'touch', 'touchscreen', 'mouse', 'mice', 'trackpad', 
        'touchpad', 'pen', 'stylus', 'video', 'button', 'lid'
    ]
    
    for i, device in enumerate(devices):
        device_name_lower = device.name.lower()
        is_excluded = any(keyword in device_name_lower for keyword in exclusion_keywords)
        is_likely_card = 'card' in device_name_lower or 'reader' in device_name_lower or 'rfid' in device_name_lower
        
        print(f"\n[{i}] {device.path}")
        print(f"    Name: {device.name}")
        print(f"    Phys: {device.phys}")
        
        capabilities = device.capabilities()
        if ecodes.EV_KEY in capabilities:
            print(f"    Type: Keyboard/HID Input Device")
            
            # Add helpful hints
            if is_likely_card:
                print(f"    ** LIKELY CARD READER **")
            elif is_excluded:
                print(f"    (Excluded: appears to be touch/mouse/other non-card device)")
            elif 'usb' in device_name_lower and 'keyboard' in device_name_lower:
                print(f"    (USB Keyboard - could be card reader)")
    
    return devices

def test_card_reader(device_index=None):
    """Test reading from a card reader device"""
    devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
    
    # Exclusion keywords (same as in main app)
    exclusion_keywords = [
        'touch', 'touchscreen', 'mouse', 'mice', 'trackpad', 
        'touchpad', 'pen', 'stylus', 'video', 'button', 'lid'
    ]
    
    if device_index is not None:
        if device_index >= len(devices):
            print(f"Error: Device index {device_index} out of range")
            return
        device = devices[device_index]
    else:
        # Try to find a card reader automatically using same logic as main app
        device = None
        
        # Priority 1: Explicit card readers
        for dev in devices:
            device_name_lower = dev.name.lower()
            if any(keyword in device_name_lower for keyword in exclusion_keywords):
                continue
            if 'card' in device_name_lower or 'reader' in device_name_lower or 'rfid' in device_name_lower or 'hid' in device_name_lower:
                capabilities = dev.capabilities()
                if ecodes.EV_KEY in capabilities:
                    device = dev
                    print(f"Found card reader: {dev.name}")
                    break
        
        # Priority 2: USB keyboards
        if not device:
            for dev in devices:
                device_name_lower = dev.name.lower()
                if any(keyword in device_name_lower for keyword in exclusion_keywords):
                    continue
                if 'usb' in device_name_lower and 'keyboard' in device_name_lower:
                    capabilities = dev.capabilities()
                    if ecodes.EV_KEY in capabilities:
                        device = dev
                        print(f"Using USB keyboard as card reader: {dev.name}")
                        break
        
        # Priority 3: Any non-excluded keyboard
        if not device:
            for dev in devices:
                device_name_lower = dev.name.lower()
                if any(keyword in device_name_lower for keyword in exclusion_keywords):
                    continue
                capabilities = dev.capabilities()
                if ecodes.EV_KEY in capabilities:
                    device = dev
                    print(f"Using keyboard device as card reader: {dev.name}")
                    break
        
        if not device:
            print("No suitable input device found!")
            return
    
    print(f"\n=== Testing Card Reader ===")
    print(f"Device: {device.name}")
    print(f"Path: {device.path}")
    print("\nSwipe your card now (press Ctrl+C to exit)...\n")
    
    card_data = ""
    
    try:
        for event in device.read_loop():
            if event.type == ecodes.EV_KEY:
                key_event = categorize(event)
                
                if key_event.keystate == 1:  # Key down
                    key_code = key_event.keycode
                    
                    # Handle Enter key (card read complete)
                    if key_code == 'KEY_ENTER':
                        print(f"\n✓ Card data received: '{card_data}'")
                        print(f"  Length: {len(card_data)} characters")
                        print(f"  Processed ID: card_{card_data.strip().upper()}")
                        print("\nReady for next card swipe...")
                        card_data = ""
                    
                    # Build card data string
                    elif key_code.startswith('KEY_'):
                        char = key_code.replace('KEY_', '')
                        if len(char) == 1:  # Single character
                            card_data += char
                            print(f"Reading: {card_data}", end='\r', flush=True)
                        elif char.isdigit():  # Handle numeric keys
                            card_data += char
                            print(f"Reading: {card_data}", end='\r', flush=True)
                            
    except KeyboardInterrupt:
        print("\n\nTest stopped by user")
    except Exception as e:
        print(f"\nError: {e}")

if __name__ == "__main__":
    print("USB Card Reader Test Tool")
    print("=" * 50)
    
    devices = list_input_devices()
    
    if not devices:
        print("\nNo input devices found!")
        exit(1)
    
    print("\n" + "=" * 50)
    choice = input("\nEnter device number to test (or press Enter for auto-detect): ").strip()
    
    if choice:
        try:
            device_index = int(choice)
            test_card_reader(device_index)
        except ValueError:
            print("Invalid device number!")
    else:
        test_card_reader()
