#!/bin/bash
set -e

HOME_DIR="/home/theia"
APP_DIR="${HOME_DIR}/app"
WORKSPACE_DIR="${HOME_DIR}/workspace"
mkdir -p "$WORKSPACE_DIR"

# ── Clone project repo ────────────────────────────────────────────────────────
if [ -n "$GITEA_REPO" ] && [ -n "$GITEA_TOKEN" ]; then
  GITEA_BASE="${GITEA_API_URL:-https://git.vibnai.com}"
  AUTH_URL="${GITEA_BASE/https:\/\//https://vibn:${GITEA_TOKEN}@}/${GITEA_REPO}.git"

  REPO_NAME=$(basename "$GITEA_REPO")
  CLONE_DIR="${WORKSPACE_DIR}/${REPO_NAME}"

  if [ ! -d "$CLONE_DIR/.git" ]; then
    echo "[startup] Cloning ${GITEA_REPO}..."
    git clone --depth=50 "$AUTH_URL" "$CLONE_DIR" 2>&1 | sed 's/vibn:[^@]*@/vibn:***@/g' || {
      echo "[startup] Clone failed — starting with empty workspace"
      CLONE_DIR="$WORKSPACE_DIR"
    }
  else
    echo "[startup] Repo present — pulling latest..."
    git -C "$CLONE_DIR" pull --ff-only 2>/dev/null || true
  fi

  git config --global credential.helper store
  printf "https://vibn:%s@%s\n" "$GITEA_TOKEN" "${GITEA_BASE#https://}" \
    > "${HOME_DIR}/.git-credentials" 2>/dev/null || true
  git config --global user.name "Vibn IDE"
  git config --global user.email "ide@vibnai.com"

  OPEN_PATH="$CLONE_DIR"
else
  echo "[startup] No GITEA_REPO/GITEA_TOKEN — empty workspace"
  OPEN_PATH="$WORKSPACE_DIR"
fi

# ── Write Theia user settings (AI keys + Gitea/Coolify prefs) ─────────────────
SETTINGS_DIR="${HOME_DIR}/.theia"
mkdir -p "$SETTINGS_DIR"

cat > "${SETTINGS_DIR}/settings.json" << SETTINGS
{
  "ai-features.AiEnable": true,
  "ai-features.google.apiKey": "${GOOGLE_API_KEY:-}",
  "ai-features.google.models": [
    "gemini-3-pro-preview",
    "gemini-3-flash-preview",
    "gemini-2.5-pro",
    "gemini-2.5-flash"
  ],
  "ai-features.chat.defaultChatAgent": "Coder",
  "ai-features.gitea.apiUrl": "${GITEA_API_URL:-https://git.vibnai.com}",
  "ai-features.gitea.apiToken": "${GITEA_TOKEN:-}",
  "ai-features.gitea.username": "${GITEA_USERNAME:-mark}",
  "editor.fontSize": 14,
  "editor.tabSize": 2,
  "files.autoSave": "afterDelay",
  "files.autoSaveDelay": 1000
}
SETTINGS

echo "[startup] Settings written"

# ── Inject vibn.css into index.html ───────────────────────────────────────────
INDEX_HTML="${APP_DIR}/lib/frontend/index.html"
if [ -f "$INDEX_HTML" ] && ! grep -q "vibn.css" "$INDEX_HTML"; then
  sed -i 's|</head>|  <link rel="stylesheet" href="./vibn.css">\n</head>|' "$INDEX_HTML"
  echo "[startup] Injected vibn.css into index.html"
fi

# ── Start Theia ───────────────────────────────────────────────────────────────
echo "[startup] Starting Theia → ${OPEN_PATH}"
exec node "${APP_DIR}/lib/backend/main.js" \
  "$OPEN_PATH" \
  --hostname=0.0.0.0 \
  --port="${PORT:-3000}"
