"""Client-side tools for agent worker (web search, URL fetch)."""

from __future__ import annotations

import json
import re

import httpx

_http = httpx.Client(timeout=15, follow_redirects=True)


def web_search(query: str, max_results: int = 5) -> str:
    """Search the web using DuckDuckGo Instant Answer API (free, no key)."""
    try:
        resp = _http.get(
            "https://api.duckduckgo.com/",
            params={"q": query, "format": "json", "no_redirect": "1"},
        )
        data = resp.json()
        results = []

        # Abstract (main answer)
        if data.get("Abstract"):
            results.append(f"**{data.get('Heading', 'Answer')}**: {data['Abstract']}")
            if data.get("AbstractURL"):
                results.append(f"Source: {data['AbstractURL']}")

        # Related topics
        for topic in data.get("RelatedTopics", [])[:max_results]:
            if isinstance(topic, dict) and topic.get("Text"):
                text = topic["Text"][:200]
                url = topic.get("FirstURL", "")
                results.append(f"- {text}" + (f" ({url})" if url else ""))

        if not results:
            return f"No results found for: {query}"

        return "\n".join(results)
    except Exception as e:
        return f"Search error: {e}"


def fetch_url(url: str) -> str:
    """Fetch a URL and extract text content (strips HTML tags)."""
    try:
        resp = _http.get(url, headers={"User-Agent": "Clawsy/1.0"})
        content_type = resp.headers.get("content-type", "")

        if "json" in content_type:
            return json.dumps(resp.json(), indent=2)[:10000]

        text = resp.text
        if "html" in content_type:
            # Simple HTML to text
            text = re.sub(r"<script[^>]*>.*?</script>", "", text, flags=re.DOTALL)
            text = re.sub(r"<style[^>]*>.*?</style>", "", text, flags=re.DOTALL)
            text = re.sub(r"<[^>]+>", " ", text)
            text = re.sub(r"\s+", " ", text).strip()

        # Limit output
        return text[:10000] if len(text) > 10000 else text
    except Exception as e:
        return f"Fetch error: {e}"


# OpenAI-compatible tool definitions for function calling
TOOL_DEFINITIONS = [
    {
        "type": "function",
        "function": {
            "name": "web_search",
            "description": "Search the web for information. Use when you need current data, facts, or research.",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "Search query"},
                },
                "required": ["query"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "fetch_url",
            "description": "Fetch and read content from a URL. Use to get specific webpage content.",
            "parameters": {
                "type": "object",
                "properties": {
                    "url": {"type": "string", "description": "URL to fetch"},
                },
                "required": ["url"],
            },
        },
    },
]

TOOL_HANDLERS = {
    "web_search": lambda args: web_search(args["query"]),
    "fetch_url": lambda args: fetch_url(args["url"]),
}
