import requests
from bs4 import BeautifulSoup
from typing import Type
from pydantic import BaseModel
from langchain.tools import BaseTool

class WebAraToolInput(BaseModel):
    konu: str

class WebAraTool(BaseTool):
    name: str = "web_ara"
    description: str = "Verilen konu ile ilgili web araması yapar ve linkleri toplar."
    args_schema: type[BaseModel] = WebAraToolInput

    async def _arun(self, *, konu: str) -> list[dict]:
        try:
            url = f"https://www.google.com/search?q={konu}"
            headers = {"User-Agent": "Mozilla/5.0"}
            res = requests.get(url, headers=headers, timeout=5)
            soup = BeautifulSoup(res.text, "html.parser")
            results = []
            for item in soup.select("div.BNeawe.vvjwJb.AP7Wnd")[:5]:
                parent = item.find_parent("a")
                link = parent["href"] if parent else ""
                results.append({"title": item.get_text(), "link": link})
            if not results:
                return [{"title": "Sonuç bulunamadı", "link": ""}]
            return results
        except Exception as e:
            return [{"title": f"Hata: {e}", "link": ""}]