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

APP_DIR="/srv/worldshaper/app"
GIT_DIR="/srv/worldshaper/repo.git"
CONTENT_ROOT="/srv/worldshaper/shared/content"
ENV_FILE="/srv/worldshaper/shared/worldshaper.env"
PORT="5180"
APP_NAME="worldshaper"

if [ -f "$ENV_FILE" ]; then
  echo "[deploy] load env"
  set -a
  # shellcheck disable=SC1090
  . "$ENV_FILE"
  set +a
fi

echo "[deploy] checkout"
git --work-tree="$APP_DIR" --git-dir="$GIT_DIR" checkout -f

cd "$APP_DIR"

echo "[deploy] install"
npm install

echo "[deploy] validate"
npm run validate:content

echo "[deploy] build"
npm run build

echo "[deploy] restart"
CONTENT_ROOT="$CONTENT_ROOT" \
PORT="$PORT" \
REQUEST_ANALYZER_AUTORUN="${REQUEST_ANALYZER_AUTORUN:-1}" \
REQUEST_ANALYZER_PROVIDER="${REQUEST_ANALYZER_PROVIDER:-deepseek}" \
REQUEST_ANALYZER_MODEL="${REQUEST_ANALYZER_MODEL:-deepseek-v4-flash}" \
REQUEST_ANALYZER_PROMOTE_THRESHOLD="${REQUEST_ANALYZER_PROMOTE_THRESHOLD:-0.85}" \
REQUEST_ANALYZER_THINKING="${REQUEST_ANALYZER_THINKING:-disabled}" \
DEEPSEEK_API_KEY="${DEEPSEEK_API_KEY:-}" \
pm2 restart "$APP_NAME" --update-env || \
CONTENT_ROOT="$CONTENT_ROOT" \
PORT="$PORT" \
REQUEST_ANALYZER_AUTORUN="${REQUEST_ANALYZER_AUTORUN:-1}" \
REQUEST_ANALYZER_PROVIDER="${REQUEST_ANALYZER_PROVIDER:-deepseek}" \
REQUEST_ANALYZER_MODEL="${REQUEST_ANALYZER_MODEL:-deepseek-v4-flash}" \
REQUEST_ANALYZER_PROMOTE_THRESHOLD="${REQUEST_ANALYZER_PROMOTE_THRESHOLD:-0.85}" \
REQUEST_ANALYZER_THINKING="${REQUEST_ANALYZER_THINKING:-disabled}" \
DEEPSEEK_API_KEY="${DEEPSEEK_API_KEY:-}" \
pm2 start server.js --name "$APP_NAME"
