#!/bin/bash
# Local development runner for Vibn Theia IDE
# Usage:
#   ./dev.sh            — full install + compile + start
#   ./dev.sh start      — start without recompiling (fastest)
#   ./dev.sh compile    — recompile changed packages + start
#   ./dev.sh watch      — recompile ai-ide package only + start

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
WORKSPACE_DIR="${HOME}/theia-workspace"
PORT="${PORT:-3000}"

cd "$SCRIPT_DIR"

# Load local env vars if present
if [ -f "${SCRIPT_DIR}/../.google.env" ]; then
  export $(grep -v '^#' "${SCRIPT_DIR}/../.google.env" | xargs) 2>/dev/null || true
fi

mkdir -p "$WORKSPACE_DIR"

MODE="${1:-full}"

install_deps() {
  if [ ! -d node_modules ]; then
    echo "→ Installing dependencies (first time, takes ~5 min)..."
    npm install --legacy-peer-deps
  else
    echo "→ Dependencies already installed."
  fi
}

compile_all() {
  echo "→ Compiling all packages..."
  NODE_OPTIONS="--max-old-space-size=4096" npm run compile
  echo "→ Building browser bundle (webpack)..."
  NODE_OPTIONS="--max-old-space-size=4096" cd examples/browser && npm run build && cd "$SCRIPT_DIR"
}

compile_ai_ide() {
  echo "→ Recompiling @theia/ai-ide only..."
  cd packages/ai-ide && npx tsc -p tsconfig.json && cd "$SCRIPT_DIR"
  echo "→ Rebuilding browser bundle..."
  NODE_OPTIONS="--max-old-space-size=4096" cd examples/browser && npm run build && cd "$SCRIPT_DIR"
}

start_theia() {
  echo ""
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo "  Vibn Theia IDE — http://localhost:${PORT}"
  echo "  Workspace: ${WORKSPACE_DIR}"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo ""

  # Write local settings.json with keys from .google.env
  mkdir -p "${HOME}/.theia"
  cat > "${HOME}/.theia/settings.json" << SETTINGS
{
  "ai-features.AiEnable": true,
  "ai-features.google.apiKey": "${GOOGLE_API_KEY:-}",
  "ai-features.google.models": [
    {
      "id": "gemini-2.0-flash",
      "name": "Gemini 2.0 Flash",
      "url": "https://generativelanguage.googleapis.com/v1beta/openai/"
    }
  ],
  "ai-features.chat.defaultChatAgent": "Coder",
  "ai-features.gitea.apiUrl": "${GITEA_API_URL:-https://git.vibnai.com}",
  "ai-features.gitea.apiToken": "${GITEA_API_TOKEN:-}",
  "ai-features.gitea.username": "${GITEA_USERNAME:-mark}",
  "editor.fontSize": 14,
  "editor.tabSize": 2,
  "files.autoSave": "afterDelay",
  "files.autoSaveDelay": 1000
}
SETTINGS

  cd examples/browser
  exec node ../../node_modules/@theia/cli/lib/theia start \
    "$WORKSPACE_DIR" \
    --hostname=0.0.0.0 \
    --port="${PORT}"
}

case "$MODE" in
  start)
    if [ ! -d "examples/browser/lib" ]; then
      echo "No compiled output found. Run './dev.sh' first."
      exit 1
    fi
    start_theia
    ;;
  compile)
    install_deps
    compile_ai_ide
    start_theia
    ;;
  full)
    install_deps
    compile_all
    start_theia
    ;;
  *)
    echo "Usage: $0 [start|compile|full]"
    exit 1
    ;;
esac
