"""
Built-in Skill: Web Search — Search the web via DuckDuckGo.
"""

from __future__ import annotations

from typing import Any

import aiohttp

from neuralclaw.cortex.action.capabilities import Capability
from neuralclaw.skills.manifest import SkillManifest, ToolDefinition, ToolParameter


async def web_search(query: str, max_results: int = 5) -> dict[str, Any]:
    """Search the web using DuckDuckGo Instant Answer API."""
    try:
        params = {"q": query, "format": "json", "no_html": "1", "skip_disambig": "1"}
        async with aiohttp.ClientSession() as session:
            async with session.get(
                "https://api.duckduckgo.com/",
                params=params,
                timeout=aiohttp.ClientTimeout(total=10),
            ) as resp:
                if resp.status != 200:
                    return {"error": f"Search failed with status {resp.status}"}
                data = await resp.json(content_type=None)

        results = []

        # Abstract (instant answer)
        if data.get("Abstract"):
            results.append({
                "title": data.get("Heading", ""),
                "snippet": data["Abstract"],
                "url": data.get("AbstractURL", ""),
            })

        # Related topics
        for topic in data.get("RelatedTopics", [])[:max_results]:
            if isinstance(topic, dict) and "Text" in topic:
                results.append({
                    "title": topic.get("Text", "")[:100],
                    "snippet": topic.get("Text", ""),
                    "url": topic.get("FirstURL", ""),
                })

        if not results:
            return {"message": f"No results found for '{query}'", "results": []}

        return {"query": query, "results": results[:max_results]}

    except Exception as e:
        return {"error": f"Search failed: {str(e)}"}


def get_manifest() -> SkillManifest:
    return SkillManifest(
        name="web_search",
        description="Search the web for information",
        capabilities=[Capability.NETWORK_HTTP],
        tools=[
            ToolDefinition(
                name="web_search",
                description="Search the web for information using DuckDuckGo",
                parameters=[
                    ToolParameter(name="query", type="string", description="Search query"),
                    ToolParameter(name="max_results", type="integer", description="Max results to return", required=False, default=5),
                ],
                handler=web_search,
            ),
        ],
    )
