"""CLI for pyvisa-ar488 — scan bus and list instruments.

Usage:
    pyvisa-ar488                          # scan /dev/ttyUSB0
    pyvisa-ar488 --port /dev/ttyACM0      # specific serial port
    pyvisa-ar488 --host 192.168.1.100     # TCP/WiFi connection
"""

import argparse
import sys


def main():
    parser = argparse.ArgumentParser(
        prog="pyvisa-ar488",
        description="Scan GPIB bus via AR488/Prologix adapter and list instruments",
    )
    parser.add_argument(
        "--port", default="/dev/ttyUSB0",
        help="Serial port (default: /dev/ttyUSB0)",
    )
    parser.add_argument(
        "--baudrate", type=int, default=115200,
        help="Serial baud rate (default: 115200)",
    )
    parser.add_argument(
        "--host",
        help="TCP host (WiFi mode — overrides --port)",
    )
    parser.add_argument(
        "--tcp-port", type=int, default=23,
        help="TCP port (default: 23)",
    )
    parser.add_argument(
        "--timeout", type=int, default=3000,
        help="Read timeout in ms (default: 3000)",
    )
    parser.add_argument(
        "--identify", action="store_true", default=True,
        help="Send *IDN? to each instrument (default: True)",
    )
    parser.add_argument(
        "--no-identify", action="store_false", dest="identify",
        help="Skip *IDN? identification",
    )

    args = parser.parse_args()

    # Create appropriate transport
    if args.host:
        from pyvisa_ar488.direct_transport import DirectTcpTransport

        transport = DirectTcpTransport(
            host=args.host,
            port=args.tcp_port,
            read_timeout_ms=args.timeout,
        )
        print(f"Connecting to AR488 at {args.host}:{args.tcp_port}...", file=sys.stderr)
    else:
        from pyvisa_ar488.direct_transport import DirectSerialTransport

        transport = DirectSerialTransport(
            port=args.port,
            baudrate=args.baudrate,
            read_timeout_ms=args.timeout,
        )
        print(f"Connecting to AR488 on {args.port}...", file=sys.stderr)

    try:
        transport.connect()
    except Exception as e:
        print(f"Connection failed: {e}", file=sys.stderr)
        sys.exit(1)

    try:
        print("Scanning GPIB bus...", file=sys.stderr)
        addresses = transport.find_listeners()

        if not addresses:
            print("No listeners found on the GPIB bus.")
            return

        print(f"\nFound {len(addresses)} instrument(s):\n")

        for addr in addresses:
            line = f"  GPIB0::{addr}::INSTR"
            if args.identify:
                try:
                    transport.set_address(addr)
                    transport.send_command("*IDN?")
                    idn = transport.read_response(timeout_ms=args.timeout)
                    line += f"  — {idn}"
                except Exception:
                    line += "  — (no *IDN? response)"
            print(line)

        print()
    finally:
        transport.disconnect()


if __name__ == "__main__":
    main()
