"""File encoding detection utilities.

This module provides functions for detecting file encodings, particularly
useful for handling Pod101 exports which often use UTF-16 encoding.
"""

from pathlib import Path


def detect_encoding(file_path: Path) -> str:
    """Detect file encoding based on Byte Order Mark (BOM).

    Pod101 exports are often encoded in UTF-16 with a BOM, while most other
    files use UTF-8. This function detects the encoding by examining the
    first two bytes of the file.

    Args:
        file_path: Path to the file to check

    Returns:
        'utf-16' if UTF-16 BOM is detected (either little-endian or big-endian),
        'utf-8-sig' otherwise (which handles UTF-8 BOM if present)

    Examples:
        >>> path = Path("pod101_export.csv")  # UTF-16 file
        >>> detect_encoding(path)
        'utf-16'
        >>> path = Path("regular_file.csv")  # UTF-8 file
        >>> detect_encoding(path)
        'utf-8-sig'

    Note:
        UTF-16 BOM can be either:
        - b'\\xff\\xfe' for little-endian (UTF-16-LE)
        - b'\\xfe\\xff' for big-endian (UTF-16-BE)

        Both are detected as 'utf-16' which Python handles automatically.
    """
    with open(file_path, "rb") as f:
        bom = f.read(2)

    # Check for UTF-16 BOMs (little-endian and big-endian)
    if bom in (b"\xff\xfe", b"\xfe\xff"):
        return "utf-16"

    # Default to UTF-8 with BOM handling
    return "utf-8-sig"
