#!/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


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

    def __init__(self, argv):
        self._test_ports = None
        self._sn = 0
        self._automatic = False
        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."""
        parser = argparse.ArgumentParser(
            description="USB Hub Speed Test CLI - Tests device enumeration speeds across multiple ports and data rate configurations.",
            epilog="Use --help_extended for detailed documentation from the README.",
            formatter_class=argparse.RawDescriptionHelpFormatter
        )
        
        parser.add_argument(
            "-t", "--test_ports",
            type=int,
            nargs="+",
            default=None,
            help="List of ports to test. If not specified, automatic port discovery is used."
        )
        
        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:])
        
        # Handle --help_extended
        if args.help_extended:
            print(read_readme_as_help(__file__))
            sys.exit(0)
        
        self._sn = args.sn
        
        # Handle test_ports - if not specified, use automatic mode
        if args.test_ports:
            # Manual mode - use provided ports
            self._automatic = False
            self._test_ports = args.test_ports
            print("Testing ports: %s" % (self._test_ports))
        else:
            # Automatic mode (default)
            self._automatic = True
            self._test_ports = None  # Will be populated during automatic discovery
            print("Automatic port discovery enabled")
        
        if self._sn:
            print("Target serial number: 0x%08X" % (self._sn))

    @property
    def test_ports(self):
        return self._test_ports
    
    @test_ports.setter
    def test_ports(self, value):
        self._test_ports = value

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

