"""Search the web using DuckDuckGo.

Returns titles, URLs, and snippets from web search results.
"""

from core.pathways.models.tool import ToolOutput


async def run(
    query: str,
    max_results: int = 5,
    region: str = "wt-wt",
) -> ToolOutput:
    """
    Args:
        query: Search query string
        max_results: Maximum results to return (default 5, max 10)
        region: Region code like 'us-en', 'uk-en' (default: no region).
    """
    if not query or not query.strip():
        return ToolOutput(
            success=False,
            error="query is required",
            data={"query": query, "results": []},
        )

    max_results = min(int(max_results), 10)

    try:
        from ddgs import DDGS
    except ImportError:
        try:
            from duckduckgo_search import DDGS
        except ImportError:
            return ToolOutput(
                success=False,
                error="ddgs not installed. Run: pip install ddgs",
                data={"query": query, "results": []},
            )

    try:
        ddgs = DDGS()
        results = [
            {
                "title": r.get("title", ""),
                "url": r.get("href", r.get("url", r.get("link", ""))),
                "snippet": r.get("body", r.get("snippet", "")),
            }
            for r in ddgs.text(query, region=region, max_results=max_results)
        ]

        urls = [str(r.get("url", "")) for r in results if r.get("url")]
        return ToolOutput(
            success=True,
            data={"query": query, "results": results, "urls": urls},
        )

    except Exception as e:
        return ToolOutput(
            success=False,
            error=str(e),
            data={"query": query, "results": []},
        )
