"""
Built-in tool: web_search

Uses the Brave Search API to return top 3 search results.

Environment variable required:
    BRAVE_API_KEY — Brave Search API key. Set in .env.

If BRAVE_API_KEY is not set, returns an informative error message instead of
raising an exception (graceful degradation for agents without search configured).
"""

from __future__ import annotations

import logging
import os

import httpx

logger = logging.getLogger(__name__)

_BRAVE_API_URL = "https://api.search.brave.com/res/v1/web/search"
_BRAVE_TIMEOUT = httpx.Timeout(timeout=15.0, connect=5.0)
_MAX_RESULTS = 3


async def web_search(query: str) -> str:
    """
    Search the web using Brave Search API.

    Args:
        query: The search query string.

    Returns:
        Formatted string with top 3 search results (title + URL + description),
        or an error message if the API is unavailable.
    """
    api_key = os.getenv("BRAVE_API_KEY", "")
    if not api_key:
        return (
            "Web search is not configured. "
            "Set the BRAVE_API_KEY environment variable to enable web search."
        )

    try:
        async with httpx.AsyncClient(timeout=_BRAVE_TIMEOUT) as client:
            response = await client.get(
                _BRAVE_API_URL,
                headers={
                    "Accept": "application/json",
                    "Accept-Encoding": "gzip",
                    "X-Subscription-Token": api_key,
                },
                params={"q": query, "count": _MAX_RESULTS},
            )
            response.raise_for_status()
    except httpx.HTTPStatusError as exc:
        logger.warning("Brave Search API error: %s", exc.response.status_code)
        return f"Web search failed: HTTP {exc.response.status_code}"
    except httpx.RequestError as exc:
        logger.warning("Brave Search connection error: %s", exc)
        return "Web search is unavailable right now. Please try again later."

    data = response.json()
    results = data.get("web", {}).get("results", [])

    if not results:
        return f"No results found for: {query}"

    lines = [f"Search results for: {query}\n"]
    for i, item in enumerate(results[:_MAX_RESULTS], start=1):
        title = item.get("title", "Untitled")
        url = item.get("url", "")
        description = item.get("description", "No description available.")
        lines.append(f"{i}. **{title}**\n   {url}\n   {description}\n")

    return "\n".join(lines)
