"""Lightweight Python client for the Distiller API."""

from __future__ import annotations

import argparse
import json
import os
from typing import Any

import httpx

__all__ = ["DistillerClient", "distill", "markdown", "main"]

DEFAULT_BASE_URL = "https://webdistiller.dev"


class DistillerClient:
    """Minimal client for the Distiller web-extraction API.

    Usage::

        client = DistillerClient(api_key="your-key")
        result = client.markdown("https://example.com")
        print(result["cleaned_markdown"])
    """

    def __init__(
        self,
        *,
        api_key: str | None = None,
        base_url: str | None = None,
        referrer_token: str | None = None,
        timeout: float = 30.0,
    ) -> None:
        self.base_url = (base_url or os.getenv("DISTILLER_API_BASE", DEFAULT_BASE_URL)).rstrip("/")
        self.api_key = api_key or os.getenv("DISTILLER_API_KEY")
        self.referrer_token = referrer_token or os.getenv("DISTILLER_REFERRER_TOKEN")
        self.timeout = timeout

    def _headers(self) -> dict[str, str]:
        headers: dict[str, str] = {}
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
        if self.referrer_token:
            headers["X-Distiller-Referrer"] = self.referrer_token
        return headers

    def markdown(
        self,
        url: str,
        *,
        use_browser: bool = False,
        force_refresh: bool = False,
        force_refetch: bool = False,
    ) -> dict[str, Any]:
        """Fetch cleaned Markdown for *url*."""
        return self._post(
            "/markdown", url,
            use_browser=use_browser,
            force_refresh=force_refresh,
            force_refetch=force_refetch,
        )

    def distill(
        self,
        url: str,
        *,
        use_browser: bool = False,
        force_refresh: bool = False,
        force_refetch: bool = False,
    ) -> dict[str, Any]:
        """Fetch full distillation (HTML + Markdown + text) for *url*."""
        return self._post(
            "/distill", url,
            use_browser=use_browser,
            force_refresh=force_refresh,
            force_refetch=force_refetch,
        )

    def start_paid_ai_checkout(self) -> dict[str, Any]:
        """Create a Stripe checkout session for paid AI tier."""
        resp = httpx.post(
            f"{self.base_url}/billing/checkout",
            headers=self._headers(),
            timeout=self.timeout,
        )
        resp.raise_for_status()
        return resp.json()

    def _post(
        self,
        endpoint: str,
        url: str,
        *,
        use_browser: bool = False,
        force_refresh: bool = False,
        force_refetch: bool = False,
    ) -> dict[str, Any]:
        headers = self._headers()
        body: dict[str, Any] = {"url": url, "use_browser": use_browser}
        if force_refresh:
            body["force_refresh"] = True
        if force_refetch:
            body["force_refetch"] = True
        resp = httpx.post(
            f"{self.base_url}{endpoint}",
            json=body,
            headers=headers,
            timeout=self.timeout,
        )
        try:
            resp.raise_for_status()
        except httpx.HTTPStatusError as exc:
            if exc.response is not None and exc.response.status_code == 402:
                raise RuntimeError("Payment required (402). Configure paid auth or provide payment headers.") from exc
            raise
        return resp.json()


def distill(url: str, **kwargs: Any) -> dict[str, Any]:
    """One-shot helper: ``distiller_client.distill("https://…")``."""
    return DistillerClient(**kwargs).distill(url)


def markdown(url: str, **kwargs: Any) -> dict[str, Any]:
    """One-shot helper: ``distiller_client.markdown("https://…")``."""
    return DistillerClient(**kwargs).markdown(url)


def main() -> None:
    parser = argparse.ArgumentParser(
        prog="web-distiller",
        description="Fetch cleaned content from the Distiller API.",
    )
    parser.add_argument("url", help="URL to distill")
    parser.add_argument("--api-base", default=None, help="Distiller API base URL")
    parser.add_argument("--api-key", default=None, help="API key (or set DISTILLER_API_KEY)")
    parser.add_argument("--use-browser", action="store_true", help="Force browser rendering")
    parser.add_argument("--force-refresh", action="store_true", help="Bypass response cache (content dedup still applies)")
    parser.add_argument("--force-refetch", action="store_true", help="Bypass ALL caches and re-fetch from upstream (always billed)")
    parser.add_argument(
        "--format",
        choices=("html", "markdown", "text", "json"),
        default="markdown",
        help="Output format (default: markdown)",
    )
    args = parser.parse_args()

    client = DistillerClient(api_key=args.api_key, base_url=args.api_base)

    call_kwargs = {
        "use_browser": args.use_browser,
        "force_refresh": args.force_refresh,
        "force_refetch": args.force_refetch,
    }

    if args.format in ("html", "json"):
        result = client.distill(args.url, **call_kwargs)
    else:
        result = client.markdown(args.url, **call_kwargs)

    if args.format == "html":
        print(result["cleaned_html"])
    elif args.format == "markdown":
        print(result["cleaned_markdown"])
    elif args.format == "text":
        print(result["cleaned_text"])
    else:
        print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()
