"""
Serial Port Discovery Utility

This module provides functions to discover available serial ports on the system.
It uses glob pattern matching to find serial device files in /dev/.
"""

import glob
from typing import List, Union


def get_serial_ports() -> List[str]:
    """
    獲取系統中所有可用的串口設備列表
    
    在 Linux 系統中，會搜尋以下模式的設備：
    - /dev/ttyUSB*  (USB 串口設備)
    - /dev/ttyACM*  (USB CDC ACM 設備)
    - /dev/ttyS*    (標準串口)
    
    Returns:
        List[str]: 包含所有找到的串口設備路徑的列表
        
    Example:
        >>> ports = get_serial_ports()
        >>> print(ports)
        ['/dev/ttyUSB0', '/dev/ttyUSB1', '/dev/ttyS0']
    """
    serial_ports = []
    
    # 搜尋不同類型的串口設備
    patterns = [
        '/dev/ttyUSB*',  # USB 串口轉換器
        '/dev/ttyACM*',  # USB CDC ACM 設備（如 Arduino）
        '/dev/ttyS*',    # 標準串口
    ]
    
    for pattern in patterns:
        serial_ports.extend(glob.glob(pattern))
    
    # 排序以便於閱讀
    serial_ports.sort()
    
    return serial_ports


def get_serial_ports_with_filter(filter_patterns: Union[str, List[str]] = None) -> List[str]:
    """
    獲取串口設備列表，可選擇性地使用自訂篩選模式
    
    Args:
        filter_patterns (Union[str, List[str]], optional): 
            單一或多個 glob 模式
            - 字串: '/dev/ttyUSB*'
            - 列表: ['/dev/ttyUSB*', '/dev/ttyACM*']
            如果為 None，則使用預設模式搜尋所有串口
    
    Returns:
        List[str]: 符合條件的串口設備路徑列表
        
    Example:
        >>> # 單一 pattern
        >>> ports = get_serial_ports_with_filter('/dev/ttyUSB*')
        >>> print(ports)
        ['/dev/ttyUSB0', '/dev/ttyUSB1']
        
        >>> # 多個 patterns
        >>> ports = get_serial_ports_with_filter(['/dev/ttyUSB*', '/dev/ttyACM*'])
        >>> print(ports)
        ['/dev/ttyACM0', '/dev/ttyUSB0', '/dev/ttyUSB1']
    """
    if filter_patterns is None:
        return get_serial_ports()
    
    # 統一轉成 list 處理
    if isinstance(filter_patterns, str):
        filter_patterns = [filter_patterns]
    
    serial_ports = []
    for pattern in filter_patterns:
        serial_ports.extend(glob.glob(pattern))
    
    serial_ports.sort()
    return serial_ports


if __name__ == "__main__":
    # 使用範例
    print("=== Serial Port Discovery ===\n")
    
    # 1. 獲取所有串口設備
    all_ports = get_serial_ports()
    print(f"找到 {len(all_ports)} 個串口設備:")
    for port in all_ports:
        print(f"  - {port}")
    
    print("\n" + "="*30 + "\n")
    
    # 2. 只搜尋 USB 串口
    usb_ports = get_serial_ports_with_filter('/dev/ttyUSB*')
    print(f"找到 {len(usb_ports)} 個 USB 串口設備:")
    for port in usb_ports:
        print(f"  - {port}")
    
    print("\n" + "="*30 + "\n")
    
    # 3. 只搜尋 ACM 設備
    acm_ports = get_serial_ports_with_filter('/dev/ttyACM*')
    print(f"找到 {len(acm_ports)} 個 ACM 設備:")
    for port in acm_ports:
        print(f"  - {port}")
