import argparse
from .utils import get_serial_ports, get_default_port
from .core import PDUConfig, ZSPDU

def main():
    parser = argparse.ArgumentParser(
        prog="zspdu",
        description="Smart PDU control via serial interface"
    )

    parser.add_argument("-v", "--version", action="version", version="zspdu 1.0.0")

    group = parser.add_mutually_exclusive_group()
    group.add_argument("-l", "--list", action="store_true", help="List all available serial ports")
    group.add_argument("-o", "--open", metavar="PORT", help="Open specific serial port")
    group.add_argument("-s", "--switch", metavar="PORT", help="Switch to another serial port")
    group.add_argument("--on", metavar="SOCKET", type=int, help="Turn ON specific power socket")
    group.add_argument("--off", metavar="SOCKET", type=int, help="Turn OFF specific power socket")
    group.add_argument("--on-all", action="store_true", help="Turn ON all power sockets")
    group.add_argument("--off-all", action="store_true", help="Turn OFF all power sockets")
    group.add_argument("-c", "--close", action="store_true", help="Close current port")

    args = parser.parse_args()

    # If no arguments provided, show help
    if not any(vars(args).values()):
        parser.print_help()
        return

    # Dispatch logic
    if args.list:
        print("Available ports:", get_serial_ports())
    else:
        config = PDUConfig(port=args.open or get_default_port())
        pdu = ZSPDU(config)

        if args.switch:
            print(pdu.switch_port(args.switch))
        elif args.on is not None:
            print(pdu.port_on(args.on))
        elif args.off is not None:
            print(pdu.port_off(args.off))
        elif args.on_all:
            print(pdu.port_on_all())
        elif args.off_all:
            print(pdu.port_off_all())
        elif args.close:
            pdu.close()
            print("Closed current port")
