"""Standalone Tavily search tool — does NOT participate in the feed pipeline."""

from __future__ import annotations

import json
import os
import sys


def search(
    query: str,
    max_results: int = 5,
    topic: str = "news",
    time_range: str | None = None,
    api_key: str | None = None,
) -> list[dict]:
    """Run a Tavily search and return results."""
    key = api_key or os.environ.get("TAVILY_API_KEY", "")
    if not key:
        print("Error: TAVILY_API_KEY not set", file=sys.stderr)
        sys.exit(1)

    try:
        from tavily import TavilyClient
    except ImportError:
        print("Error: tavily-python not installed. Run: pip install tavily-python", file=sys.stderr)
        sys.exit(1)

    client = TavilyClient(api_key=key)
    kwargs = {
        "query": query,
        "max_results": max_results,
        "topic": topic,
    }
    if time_range:
        kwargs["time_range"] = time_range

    response = client.search(**kwargs)
    results = response.get("results", [])
    return [
        {
            "title": r.get("title", ""),
            "url": r.get("url", ""),
            "content": r.get("content", ""),
            "score": r.get("score", 0),
        }
        for r in results
    ]


def main_search(args):
    """CLI entry point for platoon search."""
    results = search(
        query=args.query,
        max_results=args.max_results,
        topic=args.topic,
        time_range=args.time_range,
        api_key=args.api_key,
    )
    print(json.dumps(results, indent=2))
