try:
    from duckduckgo_search import DDGS
except ImportError:
    DDGS = None

from health.utils.logging_config import setup_logger

logger = setup_logger(__name__)

class WebSearchTool:
    @staticmethod
    def search_web(query: str, max_results: int = 5) -> str:
        """
        Search the web using DuckDuckGo.
        Use this for:
        1. Retrieval of latest scientific research or studies (e.g. "latest study on NAD+")
        2. Real-time news or events.
        3. External knowledge verification (e.g. "reviews of Oura Ring Gen 4")
        4. "Biohacker" community experiences (Reddit, forums, etc).
        
        Args:
            query: The search query string.
            max_results: Max number of results (default 5).
        """
        try:
            logger.info(f"Searching web for: {query}")
            results = DDGS().text(query, max_results=max_results)
            
            if not results:
                return f"No results found for query: {query}"
            
            # Format results nicely for the LLM
            formatted = [f"Search Results for '{query}':"]
            for i, res in enumerate(results, 1):
                title = res.get('title', 'No Title')
                link = res.get('href', '#')
                snippet = res.get('body', 'No content')
                formatted.append(f"\n{i}. [{title}]({link})\n   {snippet}")
            
            return "\n".join(formatted)

        except Exception as e:
            logger.error(f"Web search error: {e}")
            return f"Error performing web search: {str(e)}"
