#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
NODE_BIN=""
NPM_BIN=""

log_error() {
  echo "$1" >&2
}

find_node() {
  if command -v node >/dev/null 2>&1; then
    NODE_BIN="$(command -v node)"
    return 0
  fi

  find_vscode_node_bin && return 0

  return 1
}

find_vscode_node_bin() {
  local base_dirs=()
  local candidate=""

  if [[ -n "${VSCODE_AGENT_FOLDER:-}" ]]; then
    base_dirs+=("$VSCODE_AGENT_FOLDER")
  fi

  if [[ -n "${HOME:-}" ]]; then
    base_dirs+=(
      "$HOME/.vscode-server"
      "$HOME/.vscode-server-insiders"
    )
  fi

  for base_dir in "${base_dirs[@]}"; do
    [[ -d "$base_dir/bin" ]] || continue

    for candidate in "$base_dir"/bin/*/node; do
      if [[ -x "$candidate" ]]; then
        NODE_BIN="$candidate"
        return 0
      fi
    done
  done

  return 1
}

find_npm() {
  if command -v npm >/dev/null 2>&1; then
    NPM_BIN="$(command -v npm)"
    return 0
  fi

  return 1
}

needs_install() {
  [[ ! -d "$SCRIPT_DIR/node_modules" ]] && return 0
  [[ ! -d "$SCRIPT_DIR/node_modules/@modelcontextprotocol/sdk" ]] && return 0
  [[ ! -d "$SCRIPT_DIR/node_modules/oracledb" ]] && return 0
  [[ ! -d "$SCRIPT_DIR/node_modules/zod" ]] && return 0
  return 1
}

install_dependencies() {
  if ! find_npm; then
    log_error "npm nao encontrado. O bootstrap local do MCP Oracle precisa do npm para instalar as dependencias em $SCRIPT_DIR."
    log_error "Instale Node.js com npm ou rode a instalacao manualmente nessa pasta antes de iniciar o MCP."
    exit 1
  fi

  log_error "Dependencias do MCP Oracle ausentes ou desatualizadas. Executando npm install em $SCRIPT_DIR..."

  (
    cd "$SCRIPT_DIR"
    "$NPM_BIN" install --no-fund --no-audit
  )
}

if ! find_node; then
  log_error "Node nao encontrado. O bootstrap local do MCP Oracle precisa do Node.js para iniciar o servidor."
  log_error "Instale o Node.js no ambiente ou ajuste o PATH para um binario node valido."
  exit 1
fi

if needs_install; then
  install_dependencies
fi

exec "$NODE_BIN" "$SCRIPT_DIR/server.mjs"
