"""
Web search tool for EvenAge agents.

Uses Serper.dev API for real search results.
"""

from __future__ import annotations
import os
import json
from typing import Any

try:
    from pydantic import BaseModel, Field
except Exception:
    BaseModel = object  # type: ignore
    def Field(*a, **k):  # type: ignore
        return None

from evenage.core import tool as tool_decorator


class InputModel(BaseModel):  # type: ignore[misc]
    query: str = Field(description="Search query string")
    max_results: int = Field(default=5, ge=1, le=10, description="Maximum number of results to return")


@tool_decorator(
    name="web_search",
    description="Search the web using Serper.dev API and return up to N results as plain text."
)
def run(*args, **kwargs) -> str:
    """
    Search the web using Serper.dev API.
    Automatically adapts to any LLM-generated param keys.
    """
    # --- Extract query robustly ---
    query = (
        kwargs.get("query")
        or kwargs.get("param")
        or kwargs.get("task")
        or kwargs.get("message")
        or (args[0] if args else "")
    )
    query = str(query).strip()
    if not query:
        return "Error: Missing query parameter."

    max_results = int(kwargs.get("max_results", 5))
    api_key = os.getenv("SERPER_API_KEY")
    if not api_key:
        return "Error: SERPER_API_KEY not set. Add it to your .env file."

    try:
        import requests

        url = "https://google.serper.dev/search"
        headers = {
            "X-API-KEY": api_key,
            "Content-Type": "application/json; charset=utf-8",
        }
        payload = {"q": query}

        response = requests.post(url, headers=headers, json=payload, timeout=10)
        response.raise_for_status()
        data = response.json()

        organic = data.get("organic", [])
        if not organic:
            return f"No results found for: {query}"

        results = []
        for i, item in enumerate(organic[:max_results], 1):
            title = item.get("title", "Untitled")
            snippet = item.get("snippet", "")
            link = item.get("link", "")
            results.append(f"{i}. {title}\n   {snippet}\n   {link}")

        return "\n\n".join(results)

    except requests.exceptions.RequestException as e:
        return f"Error: HTTP failure - {e}"
    except Exception as e:
        return f"Error searching web: {str(e)}"
