from tavily import TavilyClient
from config import TAVILY_API_KEY

class TavilySearchTool:
    name = "tavily_search"

    def __init__(self):
        self.client = TavilyClient(api_key=TAVILY_API_KEY)

    async def execute(self, query: str, search_depth: str = "basic") -> dict:
        try:
            response = self.client.search(
                query=query, search_depth=search_depth,
                include_answer=True, max_results=5
            )
            results = [{"title": r.get("title", ""), "content": r.get("content", ""), "url": r.get("url", "")}
                       for r in response.get("results", [])]
            return {
                "query": query,
                "answer": response.get("answer", ""),
                "results": results,
                "summary": response.get("answer", results[0]["content"][:200] if results else "No results")
            }
        except Exception as e:
            return {"query": query, "answer": "", "results": [], "summary": f"Search failed: {str(e)}"}
