"""
Address Parser using libpostal for intelligent component extraction.
"""

from typing import Dict, List, Tuple


def parse_address_components(address: str) -> Dict[str, str]:
    """
    Parse address into semantic components using libpostal.

    Args:
        address: Raw address string in any format

    Returns:
        Dictionary with parsed components:
        - house_number: Street number
        - road: Street name
        - level: Floor/level designation
        - unit: Suite/apartment/unit designation
        - city: City name
        - state: State name or code
        - postcode: ZIP code
        - po_box: PO Box (if applicable)

    Example:
        >>> parse_address_components("128 King St FL 3 Suite 301 San Francisco CA 94107")
        {
            'house_number': '128',
            'road': 'king st',
            'level': 'fl 3',
            'unit': 'suite 301',
            'city': 'san francisco',
            'state': 'ca',
            'postcode': '94107'
        }
    """
    try:
        from postal.parser import parse_address
    except ImportError:
        raise ImportError(
            "libpostal is required. Install with: pip install postal\n"
            "Note: libpostal C library must be installed first: brew install libpostal"
        )

    # Parse using libpostal
    parsed: List[Tuple[str, str]] = parse_address(address)

    # Convert to dictionary (taking first occurrence of each label)
    components = {}
    for value, label in parsed:
        if label not in components:
            components[label] = value

    return components


def has_po_box(components: Dict[str, str]) -> bool:
    """
    Check if address is a PO Box.

    Args:
        components: Parsed address components

    Returns:
        True if address contains a PO Box
    """
    return 'po_box' in components
