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

BINARY_PATH="${AI_INDEXER_BINARY:-$(command -v ai-indexer-mcp || true)}"
if [[ -z "$BINARY_PATH" && -x "$HOME/.local/bin/ai-indexer-mcp" ]]; then
  BINARY_PATH="$HOME/.local/bin/ai-indexer-mcp"
fi
if [[ -z "$BINARY_PATH" ]]; then
  echo "Cannot find ai-indexer-mcp. Pass AI_INDEXER_BINARY=/path/to/ai-indexer-mcp" >&2
  exit 1
fi

PROJECT_DIR="${1:-$(pwd)}"
CONFIG_DIR="$PROJECT_DIR/.zed"
CONFIG_FILE="$CONFIG_DIR/settings.json"
mkdir -p "$CONFIG_DIR"

python3 - "$CONFIG_FILE" "$BINARY_PATH" <<'PY'
import json, pathlib, sys
path = pathlib.Path(sys.argv[1])
binary = sys.argv[2]
data = {}
if path.exists():
    data = json.loads(path.read_text())
data.setdefault("context_servers", {})
data["context_servers"]["ai-indexer"] = {
    "command": binary,
    "args": ["serve", "--repo", "."],
}
path.write_text(json.dumps(data, indent=2) + "\n")
PY

echo "Zed context server config written to $CONFIG_FILE"
