"""AgenLang Tool Registry - loads tools from registry/tools.json."""

import json
from html.parser import HTMLParser
from pathlib import Path
from importlib.resources import files

import requests


class _SnippetParser(HTMLParser):
    """Extract result snippets from DuckDuckGo lite HTML."""

    def __init__(self):
        super().__init__()
        self._in_snippet = False
        self._current = ""
        self.snippets = []

    def handle_starttag(self, tag, attrs):
        if tag == "td" and dict(attrs).get("class") == "result-snippet":
            self._in_snippet = True
            self._current = ""

    def handle_endtag(self, tag):
        if tag == "td" and self._in_snippet:
            self._in_snippet = False
            text = self._current.strip()
            if text:
                self.snippets.append(text)

    def handle_data(self, data):
        if self._in_snippet:
            self._current += data


def web_search(args: dict) -> str:
    """Perform a live web search via DuckDuckGo lite."""
    query = args.get("query", "")
    if not query:
        return "No query provided."
    try:
        resp = requests.get(
            "https://lite.duckduckgo.com/lite/",
            params={"q": query},
            headers={"User-Agent": "AgenLang/0.1"},
            timeout=10,
        )
        resp.raise_for_status()
        parser = _SnippetParser()
        parser.feed(resp.text)
        if parser.snippets:
            return " | ".join(parser.snippets[:3])
        return f"No snippets found for: {query}"
    except requests.RequestException as e:
        return f"Search failed: {e}"


def summarize(args: dict) -> str:
    """Summarize text by returning first 100 characters."""
    text = args.get("text", "")
    if not text:
        return "No text provided."
    truncated = text[:100].strip()
    if len(text) > 100:
        return truncated + "..."
    return truncated


def _load_registry() -> dict:
    """Load TOOLS_REGISTRY from registry/tools.json."""
    registry_path = files('agenlang') / 'registry' / 'tools.json'"
    if not registry_path.exists():
        raise FileNotFoundError(f"Tool registry not found: {registry_path}")
    data = json.loads(registry_path.read_text())
    # Enforce verified tier only (mitigate OpenClaw-style malware)
    verified_tools = {k: v for k, v in data.get("tools", {}).items() if v.get("tier") == "verified"}
    return verified_tools


TOOLS_REGISTRY = _load_registry()
