"""Error types for arxivy's arXiv API integration."""

from __future__ import annotations

from typing import Any


class ArxivError(Exception):
    """Base error for arXiv API issues."""

    def __init__(
        self,
        message: str,
        code: str = "ARXIV_ERROR",
        suggestion: str | None = None,
        status_code: int | None = None,
        retry_after: int | None = None,
    ):
        self.message = message
        self.code = code
        self.suggestion = suggestion
        self.status_code = status_code
        self.retry_after = retry_after
        super().__init__(message)

    def to_dict(self) -> dict[str, Any]:
        result: dict[str, Any] = {
            "error": {
                "code": self.code,
                "message": self.message,
            }
        }
        if self.suggestion:
            result["error"]["suggestion"] = self.suggestion
        if self.status_code is not None:
            result["error"]["status_code"] = self.status_code
        if self.retry_after is not None:
            result["error"]["retry_after"] = self.retry_after
        result["error"]["documentation"] = "https://info.arxiv.org/help/api/index.html"
        return result


class NotFoundError(ArxivError):
    """Paper not found on arXiv."""

    def __init__(self, arxiv_id: str):
        self.arxiv_id = arxiv_id
        super().__init__(
            message=f"Paper not found: {arxiv_id}",
            code="NOT_FOUND",
            suggestion="Check the arXiv ID format (e.g. 1706.03762 or hep-ph/0601001)",
        )


class NetworkError(ArxivError):
    """Network-level error contacting arXiv."""

    def __init__(self, message: str):
        super().__init__(
            message=message,
            code="NETWORK_ERROR",
            suggestion="Check your internet connection and try again",
        )


class RateLimitError(ArxivError):
    """Rate limit error (HTTP 429)."""

    def __init__(self, retry_after: int | None = None):
        super().__init__(
            message="Rate limit exceeded",
            code="RATE_LIMITED",
            suggestion=(
                "Wait and try again. arXiv asks clients to wait at least 3 seconds between requests; "
                "on shared IPs you may need to wait longer"
            ),
            status_code=429,
            retry_after=retry_after,
        )
