"""
web_search.py — Web search tool pro CyberBrain26 safe_oi.

Používá DuckDuckGo přes knihovnu ddgs (100% zdarma, bez API klíče).
Navrácená struktura je kompatibilní s LiteLLM tool calling formátem.

Použití:
    from .web_search import web_search, WEB_SEARCH_TOOL
    result = web_search("Python 3.13 release", max_results=3)
"""
from __future__ import annotations

from typing import Any


def web_search(query: str, max_results: int = 5,
               timelimit: str | None = None) -> dict[str, Any]:
    """
    Vyhledá ve veřejném webu přes DuckDuckGo.

    Args:
        query: dotaz (neprázdný string)
        max_results: 1–10, výchozí 5
        timelimit: 'd'|'w'|'m'|'y' pro den/týden/měsíc/rok, nebo None

    Returns:
        {'status': 'success', 'query': ..., 'results': [{title, url, snippet}]}
        nebo {'status': 'error', 'error': ...}
    """
    query = (query or "").strip()
    if not query:
        return {"status": "error", "error": "query required"}

    try:
        mr = min(max(int(max_results), 1), 10)
    except (TypeError, ValueError):
        mr = 5

    try:
        from ddgs import DDGS  # type: ignore[import-not-found]
    except ImportError as exc:
        return {"status": "error",
                "error": f"ddgs not installed: {exc}"}

    try:
        kwargs: dict[str, Any] = {"timeout": 10}
        if timelimit:
            kwargs["timelimit"] = timelimit

        raw = DDGS(**kwargs).text(query, max_results=mr)
        results = []
        for r in (raw or []):
            url = r.get("href") or r.get("url") or ""
            results.append({
                "title": str(r.get("title", ""))[:300],
                "url": str(url)[:2000],
                "snippet": str(r.get("body", ""))[:1500],
            })

        if not results:
            return {"status": "success", "query": query, "results": [],
                    "note": "no results"}

        return {"status": "success", "query": query, "results": results}

    except Exception as exc:
        return {"status": "error", "error": f"{type(exc).__name__}: {exc}"[:500]}


# LiteLLM / OpenAI tool calling formát
WEB_SEARCH_TOOL: dict[str, Any] = {
    "type": "function",
    "function": {
        "name": "web_search",
        "description": (
            "Vyhledá informace na veřejném webu přes DuckDuckGo. "
            "Použij, když potřebuješ aktuální informace, novinky, nebo "
            "fakta, která nemusí být v tvých trénovacích datech."
        ),
        "parameters": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Vyhledávací dotaz v přirozeném jazyce"
                },
                "max_results": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 10,
                    "description": "Počet výsledků (výchozí 5)"
                }
            },
            "required": ["query"],
            "additionalProperties": False
        }
    }
}


__all__ = ["WEB_SEARCH_TOOL", "web_search"]
