"""Exception hierarchy for the Zenhub GraphQL client."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Iterable


class ZenhubError(RuntimeError):
    """Base error for all Zenhub client failures."""


class ZenhubTransportError(ZenhubError):
    """Networking/HTTP layer failure."""


@dataclass(frozen=True, slots=True)
class GraphQLErrorItem:
    """A single GraphQL error entry as returned by the API."""

    message: str
    raw: dict[str, Any]


class ZenhubGraphQLError(ZenhubError):
    """GraphQL-level errors ("errors" field in the response)."""

    def __init__(self, message: str, *, errors: Iterable[dict[str, Any]] | None = None):
        self.errors: tuple[GraphQLErrorItem, ...] = tuple(
            GraphQLErrorItem(message=str(e.get("message", "")), raw=dict(e))
            for e in (errors or [])
            if isinstance(e, dict)
        )
        super().__init__(message)

    def is_schema_error(self) -> bool:
        """Heuristic: detect errors likely caused by schema differences."""
        msg = str(self)
        needles = (
            "Unknown argument",
            "Cannot query field",
            "Unknown type",
            "Field",
            "argument",
        )
        if any(n in msg for n in needles):
            return True
        return any(
            any(n in (item.message or "") for n in needles) for item in self.errors
        )
