"""HTTP API client for widesutra.com REST endpoints.

Usage::

    from widesutra import WideSutra

    with WideSutra() as client:
        collections = client.list_collections()
        text = client.get_text("dhammapada", 1, 1)
        results = client.search("four noble truths")
"""

from __future__ import annotations

from typing import Any

import httpx


class WideSutra:
    """Python SDK for WideSutra — Buddhist scriptures, Tipitaka, and Pali Canon.

    Provides typed access to all widesutra.com API endpoints including
    collections, books, texts, translations, figures, concepts, topics,
    and glossary.

    Args:
        base_url: API base URL. Defaults to ``https://widesutra.com``.
        timeout: Request timeout in seconds. Defaults to ``10.0``.
    """

    def __init__(
        self,
        base_url: str = "https://widesutra.com",
        timeout: float = 10.0,
    ) -> None:
        self._client = httpx.Client(
            base_url=f"{base_url.rstrip('/')}/api/v1/sutra/",
            timeout=timeout,
        )

    def _get(self, path: str, **params: Any) -> dict[str, Any]:
        resp = self._client.get(
            path,
            params={k: v for k, v in params.items() if v is not None},
        )
        resp.raise_for_status()
        result: dict[str, Any] = resp.json()
        return result

    # --- Collections --------------------------------------------------------

    def list_collections(self, tradition: str | None = None, **params: Any) -> dict[str, Any]:
        """List scripture collections (Tipitaka, Mahayana Sutras, etc.).

        Args:
            tradition: Filter by tradition (e.g. 'theravada', 'mahayana').
        """
        return self._get("collections/", tradition=tradition, **params)

    def get_collection(self, slug: str) -> dict[str, Any]:
        """Get collection details by slug (e.g. 'tipitaka').

        Args:
            slug: Collection URL slug.
        """
        return self._get(f"collections/{slug}/")

    # --- Books --------------------------------------------------------------

    def list_books(self, collection: str | None = None, **params: Any) -> dict[str, Any]:
        """List books within scripture collections.

        Args:
            collection: Filter by collection slug (e.g. 'tipitaka').
        """
        return self._get("books/", collection__slug=collection, **params)

    def get_book(self, slug: str) -> dict[str, Any]:
        """Get book details by slug (e.g. 'dhammapada', 'heart-sutra').

        Args:
            slug: Book URL slug.
        """
        return self._get(f"books/{slug}/")

    # --- Texts --------------------------------------------------------------

    def get_text(
        self,
        book: str,
        chapter: int,
        verse: int,
        translation: str = "sujato",
    ) -> dict[str, Any]:
        """Get a specific scripture text by book, chapter, and verse number.

        Args:
            book: Book slug (e.g. 'dhammapada').
            chapter: Chapter number.
            verse: Verse number within the chapter.
            translation: Translation code. Defaults to 'sujato'.
        """
        return self._get(
            "texts/",
            chapter__book__slug=book,
            chapter__number=chapter,
            number=verse,
            translation__code=translation,
        )

    def search(self, query: str, limit: int = 25, **params: Any) -> dict[str, Any]:
        """Search scripture texts by keyword.

        Args:
            query: Search query string (e.g. 'four noble truths').
            limit: Maximum number of results. Defaults to 25.
        """
        return self._get("texts/", search=query, page_size=limit, **params)

    # --- Translations -------------------------------------------------------

    def list_translations(self, **params: Any) -> dict[str, Any]:
        """List available text translations (Sujato, Thanissaro, etc.)."""
        return self._get("translations/", **params)

    def get_translation(self, code: str) -> dict[str, Any]:
        """Get translation details by code (e.g. 'sujato').

        Args:
            code: Translation code.
        """
        return self._get(f"translations/{code}/")

    # --- Figures ------------------------------------------------------------

    def list_figures(self, tradition: str | None = None, **params: Any) -> dict[str, Any]:
        """List Buddhist figures (Buddhas, bodhisattvas, monks).

        Args:
            tradition: Filter by tradition (e.g. 'theravada', 'mahayana').
        """
        return self._get("figures/", tradition=tradition, **params)

    def get_figure(self, slug: str) -> dict[str, Any]:
        """Get figure details by slug (e.g. 'siddhartha-gautama').

        Args:
            slug: Figure URL slug.
        """
        return self._get(f"figures/{slug}/")

    # --- Concepts -----------------------------------------------------------

    def list_concepts(self, category: str | None = None, **params: Any) -> dict[str, Any]:
        """List Buddhist concepts (Four Noble Truths, Noble Eightfold Path, etc.).

        Args:
            category: Filter by category.
        """
        return self._get("concepts/", category=category, **params)

    def get_concept(self, slug: str) -> dict[str, Any]:
        """Get concept details by slug (e.g. 'four-noble-truths').

        Args:
            slug: Concept URL slug.
        """
        return self._get(f"concepts/{slug}/")

    # --- Topics -------------------------------------------------------------

    def list_topics(self, **params: Any) -> dict[str, Any]:
        """List Buddhist topics and themes."""
        return self._get("topics/", **params)

    def get_topic(self, slug: str) -> dict[str, Any]:
        """Get topic details by slug.

        Args:
            slug: Topic URL slug.
        """
        return self._get(f"topics/{slug}/")

    # --- Glossary -----------------------------------------------------------

    def list_glossary(self, **params: Any) -> dict[str, Any]:
        """List Pali and Sanskrit glossary terms."""
        return self._get("glossary/", **params)

    def get_glossary_term(self, slug: str) -> dict[str, Any]:
        """Get glossary term details by slug.

        Args:
            slug: Term URL slug.
        """
        return self._get(f"glossary/{slug}/")

    # --- Lifecycle ----------------------------------------------------------

    def close(self) -> None:
        """Close the underlying HTTP client."""
        self._client.close()

    def __enter__(self) -> WideSutra:
        return self

    def __exit__(self, *_: object) -> None:
        self.close()
