"""
BLE Nordic UART Service Diagnostic Script
This will show you exactly what's being discovered
"""
import asyncio
from bleak import BleakClient, BleakScanner

# Your device name
# DEVICE_NAME = "Tmx4Pico"
DEVICE_NAME = "Tmx4Pico2W"


# Nordic UART Service UUIDs
NUS_SERVICE_UUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
UART_TX_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"  # Server TX, Client RX (notifications)
UART_RX_UUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"  # Server RX, Client TX (write)

async def main():
    print(f"Scanning for device '{DEVICE_NAME}'...")

    # Find the device
    device = await BleakScanner.find_device_by_name(DEVICE_NAME, timeout=10.0)

    if not device:
        print(f"ERROR: Device '{DEVICE_NAME}' not found!")
        return

    print(f"Found device: {device.name} ({device.address})")
    print(f"\nConnecting...")

    async with BleakClient(device, timeout=15.0) as client:
        print(f"Connected: {client.is_connected}")

        # Wait a moment for service discovery to complete
        await asyncio.sleep(1)

        # Services are auto-discovered on connection
        print("\n=== DISCOVERING SERVICES ===")
        # Just access .services to trigger discovery if needed

        # List all services
        print(f"\n=== ALL SERVICES ({len(client.services.services)} found) ===")
        for service in client.services:
            print(f"\nService: {service.uuid}")
            print(f"  Handle: {service.handle}")
            print(f"  Description: {service.description}")

            # List all characteristics for this service
            print(f"  Characteristics ({len(service.characteristics)} found):")
            for char in service.characteristics:
                print(f"    UUID: {char.uuid}")
                print(f"    Handle: {char.handle}")
                print(f"    Properties: {char.properties}")

                # List descriptors
                if char.descriptors:
                    print(f"    Descriptors:")
                    for desc in char.descriptors:
                        print(f"      UUID: {desc.uuid}, Handle: {desc.handle}")

        # Check specifically for Nordic UART Service
        print(f"\n=== CHECKING FOR NORDIC UART SERVICE ===")

        # Try to find the service
        nus_service = None
        for service in client.services:
            if service.uuid.lower() == NUS_SERVICE_UUID.lower():
                nus_service = service
                print(f"✓ Found Nordic UART Service!")
                break

        if not nus_service:
            print(f"✗ Nordic UART Service NOT FOUND")
            print(f"  Looking for: {NUS_SERVICE_UUID}")
            return

        # Check for TX characteristic (notify)
        print(f"\n=== CHECKING FOR TX CHARACTERISTIC (notify) ===")
        tx_char = None
        for char in nus_service.characteristics:
            print(f"  Checking: {char.uuid}")
            if char.uuid.lower() == UART_TX_UUID.lower():
                tx_char = char
                print(f"  ✓ Found TX characteristic!")
                print(f"    Properties: {char.properties}")
                break

        if not tx_char:
            print(f"  ✗ TX Characteristic NOT FOUND")
            print(f"    Looking for: {UART_TX_UUID}")

        # Check for RX characteristic (write)
        print(f"\n=== CHECKING FOR RX CHARACTERISTIC (write) ===")
        rx_char = None
        for char in nus_service.characteristics:
            print(f"  Checking: {char.uuid}")
            if char.uuid.lower() == UART_RX_UUID.lower():
                rx_char = char
                print(f"  ✓ Found RX characteristic!")
                print(f"    Properties: {char.properties}")
                break

        if not rx_char:
            print(f"  ✗ RX Characteristic NOT FOUND")
            print(f"    Looking for: {UART_RX_UUID}")

        # Try using get_characteristic method
        print(f"\n=== TESTING get_characteristic() METHOD ===")
        test_char = client.services.get_characteristic(UART_TX_UUID)
        print(f"get_characteristic('{UART_TX_UUID}'): {test_char}")

        test_char2 = client.services.get_characteristic(UART_RX_UUID)
        print(f"get_characteristic('{UART_RX_UUID}'): {test_char2}")

        # If we found the characteristics, try to use them
        if tx_char and rx_char:
            print(f"\n=== ATTEMPTING TO USE CHARACTERISTICS ===")

            def notification_handler(sender, data):
                print(f"Received: {data}")

            try:
                print("Enabling notifications on TX characteristic...")
                await client.start_notify(tx_char, notification_handler)
                print("✓ Notifications enabled!")

                print("Writing test data to RX characteristic...")
                test_data = b"Hello from Python!"
                await client.write_gatt_char(rx_char, test_data)
                print("✓ Data written!")

                # Wait for response
                await asyncio.sleep(2)

                print("Disabling notifications...")
                await client.stop_notify(tx_char)
                print("✓ Test complete!")

            except Exception as e:
                print(f"✗ Error during test: {e}")

        print(f"\n=== DIAGNOSTIC COMPLETE ===")

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except Exception as e:
        print(e)
