#!/bin/sh
set -e

# TomsIndex installer — works on any machine with curl
# Usage: curl -fsSL https://tomsindex.com/install.sh | sh

TOMSINDEX_URL="${TOMSINDEX_URL:-https://tomsindex.com}"

echo ""
echo "  TomsIndex Installer"
echo "  ==================="
echo ""

# ── Get API key ─────────────────────────────────────────────────────────────

if [ -z "$TOMSINDEX_API_KEY" ]; then
  echo "  Free API key: ${TOMSINDEX_URL}/quick-key  (or press Enter for the keyless trial)"
  echo ""
  if [ -t 0 ]; then
    printf "  Paste your API key: "
    read -r TOMSINDEX_API_KEY
  elif (: < /dev/tty) 2>/dev/null; then
    printf "  Paste your API key: "
    read -r TOMSINDEX_API_KEY < /dev/tty || true
  fi
  echo ""
fi

case "$TOMSINDEX_API_KEY" in
  ""|srch_*) ;;
  *)
    echo "  Error: Key should start with srch_"
    exit 1
    ;;
esac

if [ -z "$TOMSINDEX_API_KEY" ]; then
  echo "  No key: setting up the keyless trial (extract only, 20/day, nothing saved)."
  echo "  Re-run with a key from ${TOMSINDEX_URL}/quick-key for 10/min and a private index."
  echo ""
fi

MCP_URL="${TOMSINDEX_URL}/mcp"

# Registers the remote TomsIndex MCP server (${MCP_URL}) with each client found.
# Nothing is installed: clients talk to the server over HTTPS with your key.

# ── Configure Claude Code ───────────────────────────────────────────────────
CONFIGURED=0
if command -v claude >/dev/null 2>&1; then
  claude mcp remove tomsindex --scope user >/dev/null 2>&1 || true
  if [ -n "$TOMSINDEX_API_KEY" ]; then
    set -- --header "X-API-Key: ${TOMSINDEX_API_KEY}"
  else
    set --
  fi
  if claude mcp add --transport http --scope user tomsindex "$MCP_URL" "$@" >/dev/null; then
    echo "  + Claude Code configured"
    CONFIGURED=1
  else
    echo "  - Claude Code: failed (run: claude mcp add --transport http tomsindex $MCP_URL --header \"X-API-Key: <key>\")"
  fi
fi

# ── Configure Cursor (~/.cursor/mcp.json) ───────────────────────────────────
if [ -d "$HOME/.cursor" ]; then
  MCP_FILE="$HOME/.cursor/mcp.json"
  if [ -f "$MCP_FILE" ] && command -v python3 >/dev/null 2>&1; then
    MCP_FILE="$MCP_FILE" MCP_URL="$MCP_URL" TOMSINDEX_API_KEY="$TOMSINDEX_API_KEY" python3 -c '
import json, os
f = os.environ["MCP_FILE"]
try:
    cfg = json.load(open(f))
except Exception:
    raise SystemExit(1)  # unparseable: leave the file alone
entry = {"url": os.environ["MCP_URL"]}
if os.environ["TOMSINDEX_API_KEY"]:
    entry["headers"] = {"X-API-Key": os.environ["TOMSINDEX_API_KEY"]}
cfg.setdefault("mcpServers", {})["tomsindex"] = entry
json.dump(cfg, open(f, "w"), indent=2)
' || echo "  - Cursor: couldn't parse $MCP_FILE; left it unchanged. Add the tomsindex entry by hand."
  elif [ ! -f "$MCP_FILE" ]; then
    if [ -n "$TOMSINDEX_API_KEY" ]; then HEADERS=", \"headers\": { \"X-API-Key\": \"${TOMSINDEX_API_KEY}\" }"; else HEADERS=""; fi
    printf '{\n  "mcpServers": {\n    "tomsindex": { "url": "%s"%s }\n  }\n}\n' "$MCP_URL" "$HEADERS" > "$MCP_FILE"
  else
    echo "  - Cursor: $MCP_FILE exists and python3 is missing; add the tomsindex entry by hand"
  fi
  [ -f "$MCP_FILE" ] && grep -q tomsindex "$MCP_FILE" && echo "  + Cursor configured ($MCP_FILE)" && CONFIGURED=1
fi

# ── Configure Codex CLI (~/.codex/config.toml) ─────────────────────────────
if [ -d "$HOME/.codex" ]; then
  CODEX_FILE="$HOME/.codex/config.toml"
  touch "$CODEX_FILE"
  # Drop any previous [mcp_servers.tomsindex] table, then append a fresh one.
  awk '/^\[mcp_servers\.tomsindex\]/{skip=1;next} /^\[/{skip=0} !skip' "$CODEX_FILE" > "$CODEX_FILE.tmp" && mv "$CODEX_FILE.tmp" "$CODEX_FILE"
  cat >> "$CODEX_FILE" << TOMLEOF

[mcp_servers.tomsindex]
url = "${MCP_URL}"
TOMLEOF
  if [ -n "$TOMSINDEX_API_KEY" ]; then
    echo "http_headers = { \"X-API-Key\" = \"${TOMSINDEX_API_KEY}\" }" >> "$CODEX_FILE"
  fi
  echo "  + Codex CLI configured ($CODEX_FILE)"
  CONFIGURED=1
fi

# ── Summary ─────────────────────────────────────────────────────────────────

echo ""
if [ "$CONFIGURED" -eq 0 ]; then
  echo "  Nothing was configured (looked for Claude Code, Cursor, Codex CLI)."
  echo ""
  echo "  Add the server by hand:"
  echo "    URL:    ${MCP_URL}"
  echo "    Header: X-API-Key: <your key>"
else
  if [ -n "$TOMSINDEX_API_KEY" ]; then
    echo "  Done. Your agent now has: extract, index_search, index_get."
  else
    echo "  Done (keyless trial). Your agent now has: extract (and index_get to page long results)."
  fi
  [ -n "$TOMSINDEX_API_KEY" ] && echo "  Free while in beta. 10 requests/min per key."
fi
echo ""
echo "  Dashboard: ${TOMSINDEX_URL}/dashboard"
echo "  Docs:      ${TOMSINDEX_URL}/docs#mcp"
echo ""
