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

Usage::

    from widebible import WideBible

    with WideBible() as client:
        books = client.list_books()
        verse = client.get_verse("john", 3, 16)
        results = client.search("love")
"""

from __future__ import annotations

from typing import Any

import httpx


class WideBible:
    """Python SDK for WideBible — Bible verses, cross-references, and study tools.

    Provides typed access to all widebible.com API endpoints including
    books, verses, people, places, topics, cross-references, glossary,
    timeline, and reading plans.

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

    def __init__(
        self,
        base_url: str = "https://widebible.com",
        timeout: float = 10.0,
    ) -> None:
        self._client = httpx.Client(
            base_url=f"{base_url.rstrip('/')}/api/v1/bible/",
            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

    # ─── Books ──────────────────────────────────────────────────────────

    def list_books(self, **params: Any) -> dict[str, Any]:
        """List all 66 books of the Bible."""
        return self._get("books/", **params)

    def get_book(self, slug: str) -> dict[str, Any]:
        """Get book details by slug (e.g. 'genesis', 'john')."""
        return self._get(f"books/{slug}/")

    # ─── Book Groups ────────────────────────────────────────────────────

    def list_book_groups(self, **params: Any) -> dict[str, Any]:
        """List book groups (Pentateuch, Gospels, etc.)."""
        return self._get("book-groups/", **params)

    def get_book_group(self, slug: str) -> dict[str, Any]:
        """Get book group details by slug."""
        return self._get(f"book-groups/{slug}/")

    # ─── Translations ───────────────────────────────────────────────────

    def list_translations(self, **params: Any) -> dict[str, Any]:
        """List available Bible translations (KJV, ASV, BBE, YLT)."""
        return self._get("translations/", **params)

    def get_translation(self, code: str) -> dict[str, Any]:
        """Get translation details by code (e.g. 'kjv')."""
        return self._get(f"translations/{code}/")

    # ─── Chapters ───────────────────────────────────────────────────────

    def list_chapters(self, book: str | None = None, **params: Any) -> dict[str, Any]:
        """List chapters, optionally filtered by book slug."""
        return self._get("chapters/", book__slug=book, **params)

    # ─── Verses ─────────────────────────────────────────────────────────

    def get_verse(
        self,
        book: str,
        chapter: int,
        verse: int,
        translation: str = "kjv",
    ) -> dict[str, Any]:
        """Get a specific Bible verse by book, chapter, and verse number.

        Args:
            book: Book slug (e.g. 'john', 'genesis').
            chapter: Chapter number.
            verse: Verse number.
            translation: Translation code. Defaults to 'kjv'.
        """
        return self._get(
            "verses/",
            book__slug=book,
            chapter=chapter,
            verse=verse,
            translation__code=translation,
        )

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

        Args:
            query: Search query string.
            limit: Maximum number of results. Defaults to 25.
        """
        return self._get("verses/", search=query, page_size=limit)

    # ─── People ─────────────────────────────────────────────────────────

    def list_people(self, **params: Any) -> dict[str, Any]:
        """List biblical people (prophets, kings, apostles, etc.)."""
        return self._get("people/", **params)

    def get_person(self, slug: str) -> dict[str, Any]:
        """Get a biblical person's details by slug."""
        return self._get(f"people/{slug}/")

    # ─── Places ─────────────────────────────────────────────────────────

    def list_places(self, **params: Any) -> dict[str, Any]:
        """List biblical places with geocoded coordinates."""
        return self._get("places/", **params)

    def get_place(self, slug: str) -> dict[str, Any]:
        """Get a biblical place's details by slug."""
        return self._get(f"places/{slug}/")

    # ─── Topics ─────────────────────────────────────────────────────────

    def list_topics(self, **params: Any) -> dict[str, Any]:
        """List thematic verse collections (love, faith, prayer, etc.)."""
        return self._get("topics/", **params)

    def get_topic(self, slug: str) -> dict[str, Any]:
        """Get topic details and associated verses by slug."""
        return self._get(f"topics/{slug}/")

    # ─── Cross-References ───────────────────────────────────────────────

    def list_cross_references(self, **params: Any) -> dict[str, Any]:
        """List cross-references between Bible passages.

        Filter with ``from_book``, ``from_chapter``, ``from_verse``,
        ``to_book``, ``to_chapter``, ``to_verse``.
        """
        return self._get("cross-references/", **params)

    # ─── Glossary ───────────────────────────────────────────────────────

    def list_glossary(self, **params: Any) -> dict[str, Any]:
        """List biblical glossary terms with Hebrew/Greek words."""
        return self._get("glossary/", **params)

    def get_glossary_term(self, slug: str) -> dict[str, Any]:
        """Get a glossary term's definition by slug."""
        return self._get(f"glossary/{slug}/")

    # ─── Timeline ───────────────────────────────────────────────────────

    def list_eras(self, **params: Any) -> dict[str, Any]:
        """List biblical timeline eras (Patriarchs, Exodus, etc.)."""
        return self._get("timeline-eras/", **params)

    def list_events(self, era: str | None = None, **params: Any) -> dict[str, Any]:
        """List timeline events, optionally filtered by era slug."""
        return self._get("timeline-events/", era__slug=era, **params)

    # ─── Reading Plans ──────────────────────────────────────────────────

    def list_reading_plans(self, **params: Any) -> dict[str, Any]:
        """List Bible reading plans."""
        return self._get("reading-plans/", **params)

    def get_reading_plan(self, slug: str) -> dict[str, Any]:
        """Get a reading plan's details and daily entries by slug."""
        return self._get(f"reading-plans/{slug}/")

    # ─── Lifecycle ──────────────────────────────────────────────────────

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

    def __enter__(self) -> WideBible:
        return self

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