#!/usr/bin/env bash
# 中控一键更新：git pull + 构建前端 + pm2 reload eth-hedge-control
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# control/deploy -> repo root
REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
cd "${REPO_ROOT}"

echo "[control] pull @ ${REPO_ROOT}"
git fetch origin
git pull --ff-only origin main || git pull --ff-only

if [[ ! -d "${REPO_ROOT}/.venv" ]]; then
  python3 -m venv "${REPO_ROOT}/.venv"
fi
# shellcheck disable=SC1091
source "${REPO_ROOT}/.venv/bin/activate"
pip install -q -r "${REPO_ROOT}/requirements.txt"

echo "[control] ensure .env.control defaults (never overwrite existing values)"
cd "${REPO_ROOT}/control/backend"
python - <<'PY'
from app.envfile import ensure_env_control_defaults
wrote = ensure_env_control_defaults()
for k, v in wrote.items():
    print(f"  {k}: {'filled' if v else 'kept'}")
PY
cd "${REPO_ROOT}"

echo "[control] build frontend"
cd "${REPO_ROOT}/control/frontend"
if [[ -f package-lock.json ]]; then
  npm ci
else
  npm install
fi
npm run build

echo "[control] pm2 reload"
cd "${REPO_ROOT}"
pm2 startOrReload "${REPO_ROOT}/control/deploy/ecosystem.config.cjs" --update-env
pm2 save

echo "[control] health"
sleep 2
curl -fsS http://127.0.0.1:5160/health || true
echo
echo "[control] done"
