"""
Web Search Tool

Allows the AI agent to search the internet for information using DuckDuckGo.
"""

from pathlib import Path
from typing import Optional
from duckduckgo_search import DDGS

from ai_coder.tools.base import Tool, ToolResult, ToolResultStatus


class WebSearchTool(Tool):
    """Search the internet for information."""

    @property
    def name(self) -> str:
        return "web_search"

    @property
    def description(self) -> str:
        return """Search the internet for information using DuckDuckGo.
    
Use this tool when you need to:
- Find documentation or API references
- Look up error messages or solutions
- Research best practices
- Find code examples

Parameters:
- query (required): The search query
- max_results (optional): Maximum results (default: 5, max: 10)"""

    def execute(self, query: str, max_results: int = 5, **kwargs) -> ToolResult:
        """Execute web search and return results."""
        try:
            max_results = min(max_results, 10)  # Cap at 10 results
            
            with DDGS() as ddgs:
                results = list(ddgs.text(query, max_results=max_results))
            
            if not results:
                return ToolResult.success("No results found for the search query.")
            
            # Format results
            formatted = []
            for i, result in enumerate(results, 1):
                title = result.get("title", "No title")
                snippet = result.get("body", "No description")
                url = result.get("href", "")
                
                formatted.append(f"**{i}. {title}**\n{snippet}\nURL: {url}")
            
            output = f"Search results for: {query}\n\n" + "\n\n".join(formatted)
            
            return ToolResult.success(output)
            
        except Exception as e:
            return ToolResult.error(f"Search failed: {str(e)}")
