"""Classify an API exception as permanent, transient, or unknown."""


def classify_api_error(error: Exception) -> str:
    """Classify an API error as permanent, transient, or unknown.

    Permanent errors should not be retried (e.g. auth failures, bad requests).
    Transient errors are safe to retry (e.g. rate limits, timeouts, server errors).
    Permanent classification takes priority over transient.

    Args:
        error: The exception to classify.

    Returns:
        "permanent" | "transient" | "unknown"
    """
    parts = [str(error)]
    if error.__cause__ is not None:
        parts.append(str(error.__cause__))
    text = " ".join(parts)

    permanent_patterns = ["400", "401", "403", "Forbidden", "Unauthorized"]
    transient_patterns = [
        "429", "500", "502", "503", "504",
        "TooManyRequests", "RateLimit",
        "timeout", "Timeout",
        "ConnectionError", "Connection refused", "Connection reset",
    ]

    for pattern in permanent_patterns:
        if pattern in text:
            return "permanent"

    for pattern in transient_patterns:
        if pattern in text:
            return "transient"

    return "unknown"
