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

# Interactive setup for Neural Forge MCP stack
# - Prompts for credentials and DB config
# - Writes .env
# - Brings up Docker Compose stack
# - Applies Alembic migrations (Postgres-only)

ROOT_DIR=$(cd "$(dirname "$0")/.." && pwd)
ENV_FILE="$ROOT_DIR/.env"

say() { echo -e "\n==> $*\n"; }
ask() { local prompt="$1"; local var; read -rp "$prompt" var; echo "$var"; }

say "Neural Forge MCP bootstrap"

MCP_TOKEN=${MCP_TOKEN:-}
if [[ -z "${MCP_TOKEN}" ]]; then
  MCP_TOKEN=$(ask "Enter MCP_TOKEN (leave blank to auto-generate): ")
fi
if [[ -z "${MCP_TOKEN}" ]]; then
  MCP_TOKEN=$(python - <<'PY'
import secrets
print(secrets.token_hex(32))
PY
  )
  say "Generated secure MCP_TOKEN"
fi

# Default to PostgreSQL for real usage
PG_HOST=${PG_HOST:-postgres}
PG_PORT=${PG_PORT:-5432}
PG_DB=${PG_DB:-neural_forge}
PG_USER=${PG_USER:-forge}
PG_PASS=${PG_PASS:-forge}
echo "Configure PostgreSQL (press Enter to accept defaults):"
PG_HOST=$(ask "PG_HOST (default: $PG_HOST): ") || true; PG_HOST=${PG_HOST:-postgres}
PG_PORT=$(ask "PG_PORT (default: $PG_PORT): ") || true; PG_PORT=${PG_PORT:-5432}
PG_DB=$(ask "PG_DB (default: $PG_DB): ") || true; PG_DB=${PG_DB:-neural_forge}
PG_USER=$(ask "PG_USER (default: $PG_USER): ") || true; PG_USER=${PG_USER:-forge}
PG_PASS=$(ask "PG_PASS (default: $PG_PASS): ") || true; PG_PASS=${PG_PASS:-forge}
DATABASE_URL="postgresql+asyncpg://$PG_USER:$PG_PASS@$PG_HOST:$PG_PORT/$PG_DB"

say "Configuring Grafana credentials"
GF_ADMIN_USER_DEFAULT=${GF_SECURITY_ADMIN_USER:-admin}
read -rp "Grafana admin user (default: $GF_ADMIN_USER_DEFAULT): " GF_ADMIN_USER_INPUT || true
GF_SECURITY_ADMIN_USER=${GF_ADMIN_USER_INPUT:-$GF_ADMIN_USER_DEFAULT}

GF_SECURITY_ADMIN_PASSWORD=${GF_SECURITY_ADMIN_PASSWORD:-}
if [[ -z "${GF_SECURITY_ADMIN_PASSWORD}" ]]; then
  read -rp "Grafana admin password (leave blank to auto-generate): " GF_SECURITY_ADMIN_PASSWORD || true
fi
if [[ -z "${GF_SECURITY_ADMIN_PASSWORD}" ]]; then
  GF_SECURITY_ADMIN_PASSWORD=$(python - <<'PY'
import secrets
print(secrets.token_urlsafe(24))
PY
  )
  say "Generated secure Grafana admin password"
fi

GRAFANA_ENABLE_ANONYMOUS=${GRAFANA_ENABLE_ANONYMOUS:-false}

say "Writing .env"
cat > "$ENV_FILE" <<ENV
# Generated by scripts/bootstrap.sh
MCP_TOKEN=$MCP_TOKEN
DATABASE_URL=$DATABASE_URL
# Postgres (compose defaults)
POSTGRES_DB=${PG_DB:-neural_forge}
POSTGRES_USER=${PG_USER:-forge}
POSTGRES_PASSWORD=${PG_PASS:-forge}
# Grafana
GF_SECURITY_ADMIN_USER=$GF_SECURITY_ADMIN_USER
GF_SECURITY_ADMIN_PASSWORD=$GF_SECURITY_ADMIN_PASSWORD
GRAFANA_ENABLE_ANONYMOUS=$GRAFANA_ENABLE_ANONYMOUS
ENV

say "Starting PostgreSQL"
( cd "$ROOT_DIR" && docker compose up -d postgres )

say "Waiting for Postgres to be healthy"
for i in {1..30}; do
  if docker ps --format '{{.Names}} {{.Status}}' | grep -q 'nf-postgres.*(healthy)'; then
    break
  fi
  sleep 2
done

say "Applying database migrations (Alembic inside container)"
( cd "$ROOT_DIR" && docker compose run --rm migrate )

say "Starting services"
( cd "$ROOT_DIR" && docker compose up -d server prometheus grafana )

say "Validating MCP server"
BASE="http://127.0.0.1:8081"
curl -fsS "$BASE/get_capabilities" -H "Authorization: Bearer $MCP_TOKEN" >/dev/null && echo "MCP is up at $BASE"

echo "\nDone. Connect to MCP using:"
echo "  URL: $BASE"
echo "  Bearer token: $MCP_TOKEN"
echo "  Header: Authorization: Bearer $MCP_TOKEN"
echo "Prometheus: http://localhost:9090"
echo "Grafana:    http://localhost:3000"
echo "  user:     $GF_SECURITY_ADMIN_USER"
echo "  password: $GF_SECURITY_ADMIN_PASSWORD"
if [[ "${GRAFANA_ENABLE_ANONYMOUS}" == "true" ]]; then
  echo "  anonymous access ENABLED (dev only)"
else
  echo "  anonymous access disabled"
fi
echo "\nWindsurf/Cursor config snippet (paste into: $HOME/.codeium/windsurf/mcp_config.json):"
cat <<JSON
{
  "mcpServers": {
    "neural-forge": {
      "serverUrl": "${BASE}/sse",
      "headers": {
        "Authorization": "Bearer ${MCP_TOKEN}"
      },
      "env": { "MCP_TOKEN": "${MCP_TOKEN}" }
    }
  }
}
JSON

echo "\nAlternative (uses npx supergateway to proxy SSE; requires Node.js/npm):"
cat <<JSON
{
  "mcpServers": {
    "neural-forge": {
      "command": "npx",
      "args": ["-y", "supergateway", "--sse", "${BASE}/sse", "--header", "Authorization: Bearer ${MCP_TOKEN}"]
    }
  }
}
JSON
