#!/usr/bin/env bash
#
# AiIndexer - Codex MCP Setup
# Registers ai-indexer as a native MCP server in ~/.codex/config.toml.
#
set -euo pipefail

BOLD='\033[1m'
DIM='\033[2m'
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
RESET='\033[0m'

info()    { printf "${BLUE}[INFO]${RESET}  %s\n" "$*"; }
success() { printf "${GREEN}[  OK]${RESET}  %s\n" "$*"; }
warn()    { printf "${YELLOW}[WARN]${RESET}  %s\n" "$*"; }
error()   { printf "${RED}[FAIL]${RESET}  %s\n" "$*" >&2; }
die()     { error "$@"; exit 1; }

BINARY_PATH="${AI_INDEXER_BINARY:-}"
REPO_PATH=""
SERVER_NAME="ai-indexer"

while [[ $# -gt 0 ]]; do
    case "$1" in
        --binary) BINARY_PATH="$2"; shift 2 ;;
        --repo) REPO_PATH="$2"; shift 2 ;;
        --name) SERVER_NAME="$2"; shift 2 ;;
        --help|-h)
            echo "Usage: setup-codex.sh [--repo /path/to/project] [--binary /path/to/ai-indexer-mcp] [--name ai-indexer]"
            echo ""
            echo "Flags:"
            echo "  --repo      Repository path served by AiIndexer (default: current directory)"
            echo "  --binary    Path to ai-indexer-mcp binary"
            echo "  --name      Codex MCP server name (default: ai-indexer)"
            exit 0
            ;;
        *) die "Unknown option: $1" ;;
    esac
done

if [[ -z "$REPO_PATH" ]]; then
    REPO_PATH="$(pwd)"
fi
if [[ ! -d "$REPO_PATH" ]]; then
    die "Repository path does not exist: ${REPO_PATH}"
fi
cd "$REPO_PATH"
REPO_PATH="$(pwd)"

if [[ -z "$BINARY_PATH" ]]; then
    if command -v ai-indexer-mcp &>/dev/null; then
        BINARY_PATH="$(command -v ai-indexer-mcp)"
    elif [[ -x "${HOME}/.local/bin/ai-indexer-mcp" ]]; then
        BINARY_PATH="${HOME}/.local/bin/ai-indexer-mcp"
    elif [[ -x "${HOME}/.cargo/bin/ai-indexer-mcp" ]]; then
        BINARY_PATH="${HOME}/.cargo/bin/ai-indexer-mcp"
    elif [[ -x "/usr/local/bin/ai-indexer-mcp" ]]; then
        BINARY_PATH="/usr/local/bin/ai-indexer-mcp"
    else
        SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
        PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
        if [[ -x "${PROJECT_DIR}/target/release/ai-indexer-mcp" ]]; then
            BINARY_PATH="${PROJECT_DIR}/target/release/ai-indexer-mcp"
        else
            die "Cannot find ai-indexer-mcp binary. Build first or pass --binary /path/to/binary"
        fi
    fi
fi

if [[ ! -x "$BINARY_PATH" ]]; then
    die "Binary is not executable: ${BINARY_PATH}"
fi

info "Using binary: ${BINARY_PATH}"
info "Repo served by MCP: ${REPO_PATH}"

if ! "$BINARY_PATH" version &>/dev/null; then
    warn "Binary found but 'version' command failed. Continuing anyway..."
fi

CONFIG_DIR="${HOME}/.codex"
CONFIG_FILE="${CONFIG_DIR}/config.toml"
mkdir -p "$CONFIG_DIR"

if [[ -f "$CONFIG_FILE" ]]; then
    BACKUP="${CONFIG_FILE}.backup.$(date +%Y%m%d_%H%M%S)"
    cp "$CONFIG_FILE" "$BACKUP"
    success "Backup created: ${BACKUP}"
else
    info "Creating ${CONFIG_FILE}"
fi

if ! command -v python3 &>/dev/null; then
    die "python3 required for safe TOML block merging."
fi

python3 - "$CONFIG_FILE" "$SERVER_NAME" "$BINARY_PATH" "$REPO_PATH" <<'PYEOF'
import pathlib
import sys

config_path = pathlib.Path(sys.argv[1])
server_name = sys.argv[2]
binary_path = sys.argv[3]
repo_path = sys.argv[4]

def toml_string(value: str) -> str:
    return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'

header = f"[mcp_servers.{server_name}]"
descendant_prefix = f"[mcp_servers.{server_name}."
lines = config_path.read_text().splitlines() if config_path.exists() else []
out = []
skipping = False

for line in lines:
    stripped = line.strip()
    is_header = stripped.startswith("[") and stripped.endswith("]")
    if is_header and (stripped == header or stripped.startswith(descendant_prefix)):
        skipping = True
        continue
    if skipping and is_header:
        skipping = False
    if not skipping:
        out.append(line)

while out and out[-1].strip() == "":
    out.pop()

if out:
    out.append("")

out.extend([
    header,
    f"command = {toml_string(binary_path)}",
    "args = [",
    '    "serve",',
    '    "--repo",',
    f"    {toml_string(repo_path)},",
    "]",
])

config_path.write_text("\n".join(out) + "\n")
PYEOF

printf "\n"
success "Codex MCP configuration written to ${CONFIG_FILE}"
printf "\n"
printf "  ${BOLD}Server:${RESET} %s\n" "$SERVER_NAME"
printf "  ${BOLD}Repo:${RESET}   %s\n" "$REPO_PATH"
printf "\n"
printf "  ${BOLD}${CYAN}Next steps:${RESET}\n"
printf "  1. Restart Codex\n"
printf "  2. Ask Codex to work on code normally\n"
printf "  3. Codex can call ${DIM}context${RESET}, ${DIM}search${RESET}, ${DIM}navigate${RESET}, ${DIM}remember${RESET}, and ${DIM}status${RESET} natively\n"
printf "\n"
