"""Наружу — только класс причины: текст ошибки движка несёт адрес сервера и детали стека."""
import re

_AUTH = re.compile(r"\b40[13]\b|unauthori[sz]ed|forbidden|invalid[ _-]?(token|api[ _-]?key|credentials)|access denied", re.I)
_UNREACHABLE = re.compile(
    r"timed? ?out|timeout|connect(ion)? ?(error|refused|reset)|name or service not known|nodename|"
    r"temporary failure in name resolution|getaddrinfo|unreachable|cancellederror|\b5\d\d\b|ssl",
    re.I,
)

# `configured` — подключение в этом процессе ещё не пробовали.
_STATES = {"connected", "connecting", "failed", "disabled"}


def connection_of(status: dict) -> dict | None:
    state = status.get("status")
    if state not in _STATES:
        return None
    if state == "connected":
        return {"state": "connected", "tools": int(status.get("tools") or 0)}
    if state == "failed":
        return {"state": "failed", "reason": _reason(status.get("http_status"), str(status.get("error") or ""))}
    return {"state": state}


def _reason(http_status: int | None, error: str) -> str:
    if http_status in (401, 403):
        return "auth"
    if http_status and http_status >= 500:
        return "unreachable"
    if _AUTH.search(error):
        return "auth"
    if _UNREACHABLE.search(error):
        return "unreachable"
    return "other"
