"""HTTP client for DropThe.org WordPress REST API and public data."""

from __future__ import annotations

import httpx

WP_API = "https://dropthe.org/wp-json/wp/v2"
SITE_URL = "https://dropthe.org"


class DropTheClient:
    """Client for querying DropThe.org's public data.

    Uses the WordPress REST API (no authentication required for read access).

    Examples:
        >>> from dropthe import DropTheClient
        >>> client = DropTheClient()
        >>> posts = client.articles(per_page=5)
        >>> posts[0]["title"]["rendered"]
        'Some Article Title'

    Docs: https://dropthe.org/good/methodology/
    """

    def __init__(self, timeout: float = 30.0):
        self._http = httpx.Client(timeout=timeout)

    def close(self):
        self._http.close()

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

    def articles(
        self,
        *,
        search: str | None = None,
        per_page: int = 10,
        page: int = 1,
        categories: list[int] | None = None,
    ) -> list[dict]:
        """Fetch published articles from DropThe.org.

        Args:
            search: Search term for article titles/content.
            per_page: Results per page (default 10, max 100).
            page: Page number.
            categories: Filter by WordPress category IDs.

        Returns:
            List of article dicts from the WordPress REST API.
        """
        params: dict = {
            "per_page": min(per_page, 100),
            "page": page,
            "_fields": "id,title,slug,date,excerpt,link,categories",
        }
        if search:
            params["search"] = search
        if categories:
            params["categories"] = ",".join(str(c) for c in categories)
        resp = self._http.get(f"{WP_API}/posts", params=params)
        resp.raise_for_status()
        return resp.json()

    def article(self, slug: str) -> dict | None:
        """Get a single article by slug.

        Args:
            slug: Article URL slug.

        Returns:
            Article dict or None.
        """
        resp = self._http.get(f"{WP_API}/posts", params={
            "slug": slug,
            "_fields": "id,title,slug,date,content,excerpt,link,categories",
        })
        resp.raise_for_status()
        rows = resp.json()
        return rows[0] if rows else None

    def categories(self) -> list[dict]:
        """List all content categories.

        Returns:
            List of category dicts with id, name, slug, count.
        """
        resp = self._http.get(f"{WP_API}/categories", params={
            "per_page": 100,
            "_fields": "id,name,slug,count",
        })
        resp.raise_for_status()
        return resp.json()

    def entity_url(self, slug: str) -> str:
        """Build the DropThe.org URL for an entity.

        Args:
            slug: Entity slug (e.g., 'inception-2010', 'bitcoin').

        Returns:
            Full URL string.
        """
        return f"{SITE_URL}/entity/{slug}/"
