#!/usr/bin/env python3
"""Check RNS interface initialization state.

Diagnostic tool to inspect which RNS interfaces actually loaded and their
connection status. Use this to debug why TCPClientInterface might not be connecting.
"""

import sys
from pathlib import Path

# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))

try:
    import RNS
    from styrene.services.rns_service import get_rns_service
except ImportError as e:
    print(f"Error importing RNS: {e}")
    sys.exit(1)


def main():
    """Check RNS service and interface state."""
    print("=== RNS Interface Diagnostic ===\n")

    # Check if RNS service is initialized
    rns_service = get_rns_service()
    print(f"RNS Service initialized: {rns_service.is_initialized}")

    if not rns_service.is_initialized:
        print("\n❌ RNS not initialized. Run with Styrene services active.")
        return 1

    print(f"RNS Instance: {rns_service.reticulum_instance}\n")

    # Get RNS Transport interfaces
    try:
        interfaces = RNS.Transport.interfaces
        print(f"Total interfaces: {len(interfaces)}\n")

        for i, interface in enumerate(interfaces, 1):
            print(f"Interface #{i}:")
            print(f"  Name: {interface.name if hasattr(interface, 'name') else 'N/A'}")
            print(f"  Type: {type(interface).__name__}")

            # Check if it's a TCPClientInterface
            if "TCPClient" in type(interface).__name__:
                print(f"  ✓ TCPClientInterface found!")
                if hasattr(interface, "target_ip"):
                    print(f"    Target: {interface.target_ip}:{interface.target_port}")
                if hasattr(interface, "online"):
                    print(f"    Online: {interface.online}")

            # Check if it's AutoInterface
            elif "AutoInterface" in type(interface).__name__:
                print(f"  ✓ AutoInterface found")
                if hasattr(interface, "online"):
                    print(f"    Online: {interface.online}")

            # Generic interface info
            if hasattr(interface, "online"):
                status = "UP" if interface.online else "DOWN"
                print(f"  Status: {status}")

            if hasattr(interface, "rxb"):
                print(f"  RX bytes: {interface.rxb}")
            if hasattr(interface, "txb"):
                print(f"  TX bytes: {interface.txb}")

            print()

        # Check for TCPClientInterface specifically
        tcp_clients = [
            i for i in interfaces if "TCPClient" in type(i).__name__
        ]
        if not tcp_clients:
            print("⚠️  WARNING: No TCPClientInterface found!")
            print("   Expected interface to 192.168.0.102:4242 is missing.")
            print()
            print("   Possible causes:")
            print("   - Config not loaded by RNS")
            print("   - Interface disabled in config")
            print("   - Config syntax error preventing load")
            print("   - RNS using different config path")

        return 0

    except Exception as e:
        print(f"❌ Error accessing RNS interfaces: {e}")
        import traceback
        traceback.print_exc()
        return 1


if __name__ == "__main__":
    sys.exit(main())
