"""Client for the Wikipedia REST API, version 1."""
from dataclasses import dataclass

import click
import desert
import marshmallow
import requests

API_URL: str = "https://{}.wikipedia.org/api/rest_v1/page/random/summary"


@dataclass
class Page:
    """Page resource.

    Attributes:
        title: The title of the Wikipedia page.
        extract: A plain text summary.
    """

    title: str
    extract: str


page_schema = desert.schema(Page, meta={"unknown": marshmallow.EXCLUDE})


def random_page(language: str) -> Page:
    """Return a random page.

    Performs a GET request to the /page/random/summary endpoint.

    Args:
        language: The Wikipedia language edition. By default, the
            English Wikipedia is used ("en").

    Returns:
        A page resource.

    Raises:
        ClickException: The HTTP request failed or the HTTP response
            contained an invalid body.

    Example:
        >>> from hypermodern import wikipedia
        >>> page = wikipedia.random_page(language="en")
        >>> bool(page.title)
        True
    """
    try:
        with requests.get(API_URL.format(language)) as response:
            response.raise_for_status()
            return page_schema.load(response.json())

    except (requests.RequestException, marshmallow.ValidationError) as e:
        raise click.ClickException(str(e)) from e
