#!/usr/bin/env bash
set -euo pipefail

TOPIC="$*"
if [ -z "$TOPIC" ]; then
  echo "Usage: $0 <topic>"
  exit 1
fi

# Default to claude backend, but allow override via env var
BACKEND="${RESEARCH_BACKEND:-claude}"

# Specialized prompt for research
PROMPT="You are a Lead Researcher. Conduct a comprehensive investigation into '$TOPIC'.

Your goal is to provide a deep, synthesized report, not just a list of links.

Focus on:
1. **Key Insights**: What are the most important takeaways?
2. **Best Practices**: What is the current consensus or recommended approach?
3. **Emerging Trends**: What is new or changing in this field?
4. **Concrete Examples**: Provide real-world usage or code snippets where applicable.

Use the web search tool multiple times if necessary to get a complete picture. Cross-reference sources to ensure accuracy.

Output the result as a structured Markdown report with clear headings."

if [[ "$BACKEND" == "claude" ]]; then
  # Use claude -p with allowedTools to enable web search
  claude -p "$PROMPT" \
    --allowedTools "web_search,WebSearch,mcp__*"

elif [[ "$BACKEND" == "llm" ]]; then
  # Hybrid approach: Use Claude to fetch context, LLM to synthesize
  echo "Using hybrid backend: Claude (Search) -> LLM (Synthesis)..." >&2
  
  SEARCH_PROMPT="Search the web for '$TOPIC'. 
  Collect comprehensive information, including key insights, best practices, and examples.
  Do NOT summarize yet. Just dump the raw findings, facts, and excerpts from the search results.
  I will pass your output to another agent for synthesis."
  
  # 1. Fetch Context
  CONTEXT=$(claude -p "$SEARCH_PROMPT" --allowedTools "web_search,WebSearch,mcp__*")
  
  # 2. Synthesize with LLM
  # We pipe the context + original instructions to llm
  echo "$CONTEXT" | llm -s "$PROMPT"
  
elif [[ "$BACKEND" == "kagi" ]]; then
  # Kagi FastGPT backend
  
  # Check for API key in env var, then sops secret file
  if [ -z "${KAGI_API_KEY:-}" ]; then
    if [ -r "/run/secrets/api_keys/kagi" ]; then
      KAGI_API_KEY=$(cat /run/secrets/api_keys/kagi)
    else
      echo "Error: KAGI_API_KEY environment variable is required for 'kagi' backend." >&2
      echo "       OR ensure /run/secrets/api_keys/kagi exists and is readable." >&2
      exit 1
    fi
  fi

  echo "Using backend: Kagi FastGPT..." >&2
  
  # Call Kagi FastGPT API
  RESPONSE=$(curl -s -X POST "https://kagi.com/api/v0/fastgpt" \
       -H "Authorization: Bot $KAGI_API_KEY" \
       -H "Content-Type: application/json" \
       --data "{\"query\": \"$TOPIC\"}")

  # Check for errors in response
  if echo "$RESPONSE" | grep -q '"error"'; then
      ERROR_MSG=$(echo "$RESPONSE" | jq -r '.error[0].msg // .error')
      echo "Error from Kagi API: $ERROR_MSG" >&2
      exit 1
  fi

  # Extract and print the answer
  # The API returns: {"data": {"output": "The answer...", ...}}
  echo "$RESPONSE" | jq -r '.data.output'

else
  echo "Error: Unknown backend '$BACKEND'. Supported: claude, llm, kagi" >&2
  exit 1
fi
