#!/bin/bash
set -e

WORKSPACE_DIR="/home/project"
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
" "$GITEA_TOKEN" "${GITEA_BASE#https://}" \
    > /home/theia/.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) ─────────────────
# Theia reads these from ~/.theia/settings.json on startup
SETTINGS_DIR="/home/theia/.theia"
mkdir -p "$SETTINGS_DIR"

cat > "${SETTINGS_DIR}/settings.json" << SETTINGS
{
  "ai-features.openAiCustom.customOpenAiModels": [],
  "ai-features.anthropic.models": [],
  "ai-features.google.models": [
    {
      "id": "gemini-2.0-flash",
      "name": "Gemini 2.0 Flash",
      "url": "https://generativelanguage.googleapis.com/v1beta/openai/"
    }
  ],
  "ai-features.google.apiKey": "${GOOGLE_API_KEY:-}",
  "ai-features.gitea.apiUrl": "${GITEA_API_URL:-https://git.vibnai.com}",
  "ai-features.gitea.apiToken": "${GITEA_TOKEN:-}",
  "ai-features.gitea.username": "${GITEA_USERNAME:-mark}",
  "ai-features.coolify.apiUrl": "${COOLIFY_API_URL:-http://34.19.250.135:8000}",
  "ai-features.coolify.apiToken": "${COOLIFY_API_TOKEN:-}",
  "ai-features.AiEnable": true,
  "ai-features.chat.defaultChatAgent": "Coder",
  "editor.fontSize": 14,
  "editor.tabSize": 2,
  "files.autoSave": "afterDelay",
  "files.autoSaveDelay": 1000
}
SETTINGS

echo "[startup] Settings written to ${SETTINGS_DIR}/settings.json"

# ── Start sync server (agent runner calls this to trigger git pull) ───────────
if [ -f /sync-server.js ]; then
  echo "[startup] Starting sync server on :3001..."
  node /sync-server.js &
fi

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