"""
Ferramenta de busca na web
"""
import aiohttp
import asyncio
from typing import List, Dict, Optional
from urllib.parse import quote


class SearchTool:
    """
    Ferramenta de busca usando DuckDuckGo (gratuito, sem API key)
    """

    def __init__(self):
        self.base_url = "https://html.duckduckgo.com/html/"
        self.max_results = 5

    async def search(self, query: str, max_results: int = 5) -> List[Dict[str, str]]:
        """
        Busca na web e retorna resultados
        """
        self.max_results = max_results

        try:
            async with aiohttp.ClientSession() as session:
                params = {"q": quote(query)}
                headers = {
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.0"
                }

                async with session.get(
                    self.base_url,
                    params=params,
                    headers=headers
                ) as response:
                    if response.status != 200:
                        return [{"error": f"HTTP {response.status}"}]

                    html = await response.text()
                    return self._parse_results(html)

        except Exception as e:
            return [{"error": str(e)}]

    def _parse_results(self, html: str) -> List[Dict[str, str]]:
        """
        Extrai resultados do HTML
        """
        import re

        results = []
        # Pattern para resultados DuckDuckGo
        pattern = r'<a rel="nofollow" class="result__a" href="([^"]+)">([^<]+)</a>'
        matches = re.findall(pattern, html)

        for url, title in matches[:self.max_results]:
            # Limpar URL
            clean_url = url.replace("//duckduckgo.com/l/?uddg=", "")
            clean_url = clean_url.split("&rut=")[0]
            clean_url = clean_url.replace("%3A", ":").replace("%2F", "/")

            results.append({
                "title": title.strip(),
                "url": clean_url
            })

        if not results:
            return [{"info": "Nenhum resultado encontrado"}]

        return results

    async def search_news(self, query: str, max_results: int = 3) -> List[Dict[str, str]]:
        """
        Busca notícias
        """
        return await self.search(f"{query} notícias", max_results)

    def format_results(self, results: List[Dict[str, str]]) -> str:
        """
        Formata resultados para exibição
        """
        if not results:
            return "Nenhum resultado encontrado."

        lines = ["**Resultados da busca:**\n"]
        for i, result in enumerate(results, 1):
            if "error" in result:
                lines.append(f"⚠️ Erro: {result['error']}")
            elif "info" in result:
                lines.append(f"ℹ️ {result['info']}")
            else:
                lines.append(f"{i}. **{result['title']}**")
                lines.append(f"   {result['url']}\n")

        return "\n".join(lines)