"""Read a CSV file with automatic encoding fallback from utf-8 to latin-1."""
from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import pandas as pd


def safe_read_csv_fallback(path: "str | Path") -> "pd.DataFrame":
    """Read a CSV file, falling back to latin-1 if utf-8 decoding fails.

    Tries pandas read_csv with the default utf-8 encoding first. On a
    UnicodeDecodeError retries with latin-1 (ISO-8859-1), which covers most
    Western European legacy CSV exports.

    Args:
        path: Path to the CSV file.

    Returns:
        A pandas DataFrame with the CSV contents.

    Raises:
        FileNotFoundError: If the file does not exist.
        Exception: Any other pandas read error (malformed CSV, etc.).
    """
    import pandas as pd

    p = Path(path)
    try:
        return pd.read_csv(p)
    except UnicodeDecodeError:
        return pd.read_csv(p, encoding="latin-1")
