"""Web search tools."""

from pydantic_ai import RunContext
from pydantic_ai.toolsets import FunctionToolset

from pydanticai_multiagent.dependencies import SearchDeps

web_search_toolset: FunctionToolset[SearchDeps] = FunctionToolset()


@web_search_toolset.tool
async def search_web(
    ctx: RunContext[SearchDeps],
    query: str,
    num_results: int = 5,
) -> str:
    """Search the web for information.

    Args:
        ctx: The run context with dependencies.
        query: Search query string.
        num_results: Number of results to return (1-10).
    """
    # Example implementation - replace with actual search API
    response = await ctx.deps.http_client.get(
        "https://api.search.example.com/search",
        params={"q": query, "limit": min(num_results, 10)},
        headers={"Authorization": f"Bearer {ctx.deps.search_api_key}"},
    )
    results = response.json().get("results", [])

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

    formatted = []
    for i, r in enumerate(results, 1):
        formatted.append(f"{i}. [{r.get('title', 'Untitled')}]({r.get('url', '')})")
        formatted.append(f"   {r.get('snippet', '')}")

    return "\n".join(formatted)


@web_search_toolset.tool
async def fetch_webpage(
    ctx: RunContext[SearchDeps],
    url: str,
) -> str:
    """Fetch and extract content from a webpage.

    Args:
        ctx: The run context with dependencies.
        url: The URL to fetch.
    """
    response = await ctx.deps.http_client.get(url)
    # In production, use a proper HTML parser
    content = str(response.content)

    # Truncate if too long
    max_length = 4000
    if len(content) > max_length:
        content = content[:max_length] + "...[truncated]"

    return content
