#! /usr/bin/env python3
import argparse
import sys
import logging
import serial

logger = logging.getLogger(__name__)


def main() -> int:
    # Handle program arguments
    ap = argparse.ArgumentParser(
        prog="kxtune", description="Tune a KX2 or KX3 to a new frequency"
    )
    ap.add_argument("frequency", help="Frequency to tune to in KC", type=float)
    ap.add_argument("--vfo", help="VFO to tune", choices=["a", "b"], default="a")
    ap.add_argument(
        "--mode",
        help="Radio mode",
        choices=["lsb", "usb", "cw", "fm", "am", "data", "cw-r", "data-r"],
    )
    ap.add_argument("--device", "-d", help="Serial device", default="/dev/ttyUSB0")
    ap.add_argument("--baud", "-b", help="Serial baud rate", default=38400, type=int)
    ap.add_argument(
        "-v", "--verbose", help="Enable verbose logging", action="store_true"
    )
    args = ap.parse_args()

    # Configure logging
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(levelname)s:	%(message)s",
    )

    # Convert to Hz
    frequency = int(args.frequency * 1000)

    # Connect to the radio
    logger.debug(f"Connecting to radio: {args.device}")
    serial_conn = serial.Serial(args.device, args.baud)

    # Send the tune command
    cmd = f"F{args.vfo.upper()}{frequency:011d};"
    logger.debug(f"Sending command: {cmd}")
    serial_conn.write(cmd.encode("ascii"))

    # If we have a mode, set it
    mode_id = {
        "lsb": "1",
        "usb": "2",
        "cw": "3",
        "fm": "4",
        "am": "5",
        "data": "6",
        "cw-r": "7",
        "data-r": "9",
    }.get(args.mode)
    if mode_id:
        cmd = f"MD{mode_id};"
        logger.debug(f"Sending command: {cmd}")
        serial_conn.write(cmd.encode("ascii"))

    return 0


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