#!/bin/bash
# Tavily Web Search

QUERY="${1:-}"
if [ -z "$QUERY" ]; then
    echo "Usage: search <query>"
    exit 1
fi

API_KEY="${TAVILY_API_KEY:-}"
if [ -z "$API_KEY" ]; then
    echo "Error: TAVILY_API_KEY not set"
    exit 1
fi

echo "Searching: $QUERY"
curl -s -X POST "https://api.tavily.com/search" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d "{\"query\": \"$QUERY\", \"max_results\": 5, \"include_answer\": true}" | python3 -c "
import sys, json
d = json.load(sys.stdin)
if 'answer' in d and d['answer']:
    print('\n📝 Answer:')
    print(d['answer'])
print('\n🔗 Sources:')
for r in d.get('results', [])[:5]:
    print(f\"  - {r.get('title', 'No title')}\")
    print(f\"    {r.get('url', '')}\")
"
