"""Web search plugin — internet search capability."""
from __future__ import annotations

import logging

import httpx
from bs4 import BeautifulSoup

from hivemind.plugins.base import Plugin, capability

log = logging.getLogger(__name__)

# DuckDuckGo HTML search (no API key needed)
DDG_URL = "https://html.duckduckgo.com/html/"


class WebSearchPlugin(Plugin):
    name = "web_search"
    version = "0.1.0"
    description = "Search the internet and fetch web pages"

    @capability("Search the internet for information")
    async def search(self, query: str, max_results: int = 5) -> str:
        """Search DuckDuckGo and return results."""
        try:
            async with httpx.AsyncClient(timeout=15, follow_redirects=True) as client:
                resp = await client.post(DDG_URL, data={"q": query})
                resp.raise_for_status()

            soup = BeautifulSoup(resp.text, "html.parser")
            results = []
            for i, r in enumerate(soup.select(".result__body")[:max_results]):
                title_el = r.select_one(".result__title")
                snippet_el = r.select_one(".result__snippet")
                link_el = r.select_one(".result__url")
                title = title_el.get_text(strip=True) if title_el else ""
                snippet = snippet_el.get_text(strip=True) if snippet_el else ""
                link = link_el.get_text(strip=True) if link_el else ""
                results.append(f"{i+1}. **{title}**\n   {link}\n   {snippet}")

            if not results:
                return f"Keine Ergebnisse für: {query}"
            return f"Suchergebnisse für '{query}':\n\n" + "\n\n".join(results)

        except Exception as e:
            log.error("Search failed: %s", e)
            return f"Suche fehlgeschlagen: {e}"

    @capability("Fetch and read a web page")
    async def fetch(self, url: str, max_chars: int = 5000) -> str:
        """Fetch a URL and extract readable text content."""
        try:
            async with httpx.AsyncClient(timeout=15, follow_redirects=True) as client:
                resp = await client.get(url, headers={"User-Agent": "HiveMind/0.1"})
                resp.raise_for_status()

            soup = BeautifulSoup(resp.text, "html.parser")
            # Remove script/style elements
            for tag in soup(["script", "style", "nav", "footer", "header"]):
                tag.decompose()
            text = soup.get_text(separator="\n", strip=True)
            if len(text) > max_chars:
                text = text[:max_chars] + "\n\n[... truncated]"
            return text

        except Exception as e:
            log.error("Fetch failed: %s", e)
            return f"Seite konnte nicht geladen werden: {e}"


PLUGIN_CLASS = WebSearchPlugin
