"""Web search tool implementation"""

import requests
from bs4 import BeautifulSoup
from typing import Dict, Any, List


class WebSearchTool:
    """Web search tool"""
    
    def __init__(self, config: Dict[str, Any]):
        """Initialize web search tool
        
        Args:
            config: Tool configuration
        """
        self.config = config
        self.api_key = config.get('api-key', '')
        self.description = "Web search tool"
    
    def execute(self, query: str, **params) -> str:
        """Execute web search
        
        Args:
            query: Search query
            params: Additional parameters
            
        Returns:
            Search results
        """
        # For demonstration purposes, we'll use a simple web scraping approach
        # In a real implementation, you would use a proper search API
        return self._search_web(query)
    
    def _search_web(self, query: str) -> str:
        """Search the web using Google
        
        Args:
            query: Search query
            
        Returns:
            Search results
        """
        try:
            # Use Google search with a simple approach
            # Note: This is for demonstration only and may be against Google's TOS
            url = f"https://www.google.com/search?q={query.replace(' ', '+')}"
            headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
            }
            
            response = requests.get(url, headers=headers, timeout=10)
            response.raise_for_status()
            
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # Extract search results
            results = []
            for g in soup.find_all('div', class_='g'):
                title = g.find('h3')
                if title:
                    title_text = title.text
                    link = g.find('a', href=True)
                    if link:
                        link_href = link['href']
                        snippet = g.find('div', class_='VwiC3b')
                        snippet_text = snippet.text if snippet else ""
                        results.append(f"Title: {title_text}\nLink: {link_href}\nSnippet: {snippet_text}\n")
                if len(results) >= 3:  # Limit to 3 results
                    break
            
            if results:
                return "Search results:\n" + "\n".join(results)
            else:
                return "No results found"
        except Exception as e:
            return f"Error searching web: {str(e)}"
    
    def get_schema(self) -> Dict[str, Any]:
        """Get tool schema
        
        Returns:
            JSON Schema for the tool
        """
        return {
            "name": "websearch",
            "description": self.description,
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Search query"
                    }
                },
                "required": ["query"]
            }
        }
