import json
import os

import httpx

BRAVE_API_URL = "https://api.search.brave.com/res/v1/web/search"


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:
        resp = await client.get(
            BRAVE_API_URL,
            params={"q": query, "count": count},
            headers=headers,
        )
        resp.raise_for_status()
        data = resp.json()

    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)}
