TOOL_NAME = "youtube_search"
TOOL_DESCRIPTION = """Search YouTube for videos and return title, URL and description for each result. No API key required."""
TOOL_ARGS = '{"query": {"type": "string", "description": "Search query for YouTube videos"}, "max_results": {"type": "integer", "default": 10, "description": "Maximum number of results to return"}}'

import json
import requests
from tools._std import tool_ok, tool_error

def run(args: dict) -> str:
    query = args.get("query", "")
    max_results = args.get("max_results", 10)

    if not query:
        return tool_error("query parameter is required")

    yt_query = f"{query} site:youtube.com/watch"

    # Primary: DuckDuckGo (free, no API key)
    try:
        from duckduckgo_search import DDGS
        with DDGS() as ddgs:
            results = list(ddgs.text(yt_query, max_results=max_results))
            items = [{"title": r.get("title", ""), "url": r.get("href", ""), "description": r.get("body", "")} for r in results]
            result = _format_results(query, items, max_results)
            if result:
                return result
    except Exception:
        pass

    # Fallback: Brave Search (only if key configured)
    try:
        from pathlib import Path
        settings_path = Path(__file__).parent.parent / "settings.json"
        if settings_path.exists():
            settings = json.loads(settings_path.read_text(encoding="utf-8"))
            brave_key = (settings.get("brave_api_key", "") or "").strip()
            if brave_key:
                res = requests.get(
                    "https://api.search.brave.com/res/v1/web/search",
                    params={"q": yt_query, "count": max_results},
                    headers={"Accept": "application/json", "X-Subscription-Token": brave_key},
                    timeout=12,
                )
                if res.status_code == 200:
                    items = (res.json().get("web") or {}).get("results") or []
                    return _format_results(query, items, max_results)
    except Exception:
        pass

    return tool_error(f"Geen YouTube-resultaten gevonden voor: '{query}'")


def _format_results(query: str, items: list, max_results: int) -> str:
    videos = []
    seen_urls = set()
    
    for r in items:
        url = r.get("url") or r.get("href") or ""
        if "youtube.com/watch" in url and "v=" in url and url not in seen_urls:
            seen_urls.add(url)
            title = (r.get("title") or "").replace(" - YouTube", "").strip()
            desc = (r.get("description") or r.get("body") or "").strip()
            videos.append({"title": title, "url": url, "description": desc})
        if len(videos) >= max_results:
            break
    
    if not videos:
        return tool_error(f"Geen YouTube-resultaten gevonden voor: '{query}'")
    
    return tool_ok({"videos": videos}, f"{len(videos)} YouTube-resultaten voor '{query}'")
