"""Entry point: python -m debug_console [COM_PORT] [baudrate]"""
import sys

import serial.tools.list_ports

from .app import DebugConsoleApp


def select_port() -> str:
    ports = sorted(serial.tools.list_ports.comports(), key=lambda p: p.device)
    if not ports:
        print("No COM ports found.")
        sys.exit(1)

    print("Available COM ports:")
    for i, p in enumerate(ports):
        desc = f" - {p.description}" if p.description and p.description != p.device else ""
        print(f"  [{i}] {p.device}{desc}")

    while True:
        choice = input(f"\nSelect port [0-{len(ports)-1}]: ").strip()
        try:
            idx = int(choice)
            if 0 <= idx < len(ports):
                return ports[idx].device
        except ValueError:
            # Allow typing the port name directly
            for p in ports:
                if choice.upper() == p.device.upper():
                    return p.device
        print("Invalid selection, try again.")


def main():
    if len(sys.argv) >= 2:
        port = sys.argv[1]
    else:
        port = select_port()

    baudrate = int(sys.argv[2]) if len(sys.argv) > 2 else 460800

    print(f"Connecting to {port} at {baudrate} baud...")
    app = DebugConsoleApp(port, baudrate)
    app.run()


if __name__ == "__main__":
    main()
