#!/usr/bin/env python3
import argparse
import sys
import os

# Add utilities to path for readme_helper import
script_dir = os.path.dirname(os.path.abspath(__file__))
utilities_dir = os.path.abspath(os.path.join(script_dir, "../utilities"))
sys.path.insert(0, utilities_dir)
from readme_helper import read_readme_as_help
from power_supply_configs import POWER_SUPPLY_CONFIGS, KEY_EXPECTED_HOST_PDOS, KEY_EXPECTED_HOST_PDOS_VOLTAGE, KEY_EXPECTED_RDOS


class CustomArgumentParser:
    """Command-line argument parser for the RDO Test CLI script."""

    def __init__(self, argv):
        self._test_port = None
        self._dut = None
        self._sn = 0
        self._expected_host_pdos = None
        self._expected_host_pdos_voltage = None
        self._expected_rdos = None
        self._parse_arguments(argv)

    @staticmethod
    def _parse_serial_number(value):
        try:
            return int(value, 0)
        except ValueError:
            try:
                return int(value, 16)
            except ValueError:
                raise argparse.ArgumentTypeError("'%s' - use decimal or hex (0x...)" % value)

    def _parse_arguments(self, argv):
        """Parse command-line arguments."""
        # Handle --help_extended early, before argparse validates required args
        if "--help_extended" in argv:
            print(read_readme_as_help(__file__))
            sys.exit(0)
        
        parser = argparse.ArgumentParser(
            description="RDO Test CLI - Tests USB Power Delivery RDO (Request Data Object) configurations on USB Hub ports.",
            epilog="Use --help_extended for detailed documentation from the README.",
            formatter_class=argparse.RawDescriptionHelpFormatter
        )
        
        parser.add_argument(
            "-t", "--test_port",
            type=int,
            required=True,
            help="Port number under test"
        )
        
        parser.add_argument(
            "-d", "--dut",
            choices=list(POWER_SUPPLY_CONFIGS.keys()),
            required=True,
            help="Power supply to test: %s" % ", ".join(POWER_SUPPLY_CONFIGS.keys())
        )
        
        parser.add_argument(
            "-s", "--sn",
            type=self._parse_serial_number,
            default=0,
            help="Serial number of the device to connect to (hex or decimal, default: 0 = first found)"
        )
        
        parser.add_argument(
            "--help_extended",
            action="store_true",
            default=False,
            help="Show extended help from the README file and exit."
        )
        
        args = parser.parse_args(argv[1:])
        
        self._test_port = args.test_port
        self._dut = args.dut
        self._sn = args.sn
        
        # Load power supply configuration
        if self._dut not in POWER_SUPPLY_CONFIGS:
            parser.error("Unknown power supply: %s" % self._dut)
        
        config = POWER_SUPPLY_CONFIGS[self._dut]
        self._expected_host_pdos = config[KEY_EXPECTED_HOST_PDOS]
        self._expected_host_pdos_voltage = config[KEY_EXPECTED_HOST_PDOS_VOLTAGE]
        self._expected_rdos = config[KEY_EXPECTED_RDOS]

        print("Test Port: %d" % self._test_port)
        print("DUT: %s" % self._dut)
        if self._sn:
            print("Target serial number: 0x%08X" % self._sn)

    @property
    def test_port(self):
        return self._test_port

    @property
    def dut(self):
        return self._dut

    @property
    def sn(self):
        return self._sn

    @property
    def expected_host_pdos(self):
        return self._expected_host_pdos

    @property
    def expected_host_pdos_voltage(self):
        return self._expected_host_pdos_voltage

    @property
    def expected_rdos(self):
        return self._expected_rdos

