import asyncio
import json
import os

import httpx

BRAVE_API_URL = "https://api.search.brave.com/res/v1/web/search"
_MAX_RETRIES = 3
_BASE_DELAY = 2.0  # seconds


async def handler(params: dict) -> dict:
    """Search the web using Brave Search API."""
    query = params["query"]
    count = min(params.get("count") or 5, 20)

    api_key = os.environ.get("BRAVE_API_KEY")
    if not api_key:
        raise ValueError("BRAVE_API_KEY not set. Get one at https://brave.com/search/api/")

    headers = {
        "Accept": "application/json",
        "Accept-Encoding": "gzip",
        "X-Subscription-Token": api_key,
    }

    async with httpx.AsyncClient(timeout=15) as client:
        last_error = None
        for attempt in range(_MAX_RETRIES):
            resp = await client.get(
                BRAVE_API_URL,
                params={"q": query, "count": count},
                headers=headers,
            )
            if resp.status_code == 429 or resp.status_code >= 500:
                delay = _BASE_DELAY * (2 ** attempt)
                retry_after = resp.headers.get("Retry-After")
                if retry_after and retry_after.isdigit():
                    delay = max(delay, float(retry_after))
                last_error = f"HTTP {resp.status_code}"
                await asyncio.sleep(delay)
                continue
            resp.raise_for_status()
            data = resp.json()
            break
        else:
            raise httpx.HTTPStatusError(
                f"Brave API failed after {_MAX_RETRIES} retries: {last_error}",
                request=resp.request,
                response=resp,
            )

    web_results = data.get("web", {}).get("results", [])
    results = [
        {
            "title": r.get("title", ""),
            "url": r.get("url", ""),
            "snippet": r.get("description", ""),
        }
        for r in web_results[:count]
    ]

    return {"results": json.dumps(results, indent=2)}
