#!/usr/bin/env bash
# 部署脚本共用函数
INSTALL_DIR="${INSTALL_DIR:-/opt/secondary-school-grade-archive}"
WEB_PORT="${WEB_PORT:-23566}"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info()  { echo -e "${GREEN}[INFO]${NC} $*"; }
log_warn()  { echo -e "${YELLOW}[WARN]${NC} $*"; }
log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }

require_root() {
  if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
    log_error "请使用 root 运行: sudo bash $*"
    exit 1
  fi
}

load_env_port() {
  if [[ -f "${INSTALL_DIR}/.env" ]]; then
    # shellcheck disable=SC1090
    set -a && source "${INSTALL_DIR}/.env" && set +a
  fi
  WEB_PORT="${WEB_PORT:-23566}"
}

stop_legacy_pm2() {
  if command -v pm2 &>/dev/null; then
    pm2 delete grade-api grade-web 2>/dev/null || true
    pm2 save 2>/dev/null || true
    log_info "已停止旧版 PM2 进程"
  fi
}

setup_systemd_service() {
  log_info "配置 systemd 服务 grade-archive…"
  sed "s|/opt/secondary-school-grade-archive|${INSTALL_DIR}|g" \
    "${INSTALL_DIR}/deploy/grade-archive.service" > /etc/systemd/system/grade-archive.service
  systemctl daemon-reload
  systemctl enable grade-archive
}

restart_grade_service() {
  load_env_port
  mkdir -p "${INSTALL_DIR}/uploads" "${INSTALL_DIR}/backups"
  find "${INSTALL_DIR}/deploy" -name "*.sh" -exec chmod +x {} + 2>/dev/null || true
  log_info "重启 grade-archive（端口 ${WEB_PORT}）…"
  systemctl restart grade-archive
}

wait_healthy() {
  load_env_port
  local i
  for i in $(seq 1 30); do
    if curl -sf "http://127.0.0.1:${WEB_PORT}/api/health" >/dev/null 2>&1; then
      log_info "健康检查通过 — http://127.0.0.1:${WEB_PORT}"
      return 0
    fi
    sleep 2
  done
  log_error "服务未响应，请查看日志:"
  journalctl -u grade-archive -n 40 --no-pager || true
  return 1
}

install_ocr_deps_safe() {
  if [[ -x "${INSTALL_DIR}/deploy/install-ocr-deps.sh" ]]; then
    bash "${INSTALL_DIR}/deploy/install-ocr-deps.sh" || log_warn "OCR 依赖安装跳过（可稍后重试）"
  fi
}

show_service_status() {
  echo ""
  systemctl status grade-archive --no-pager -l 2>/dev/null || true
  echo ""
  ss -tlnp 2>/dev/null | grep -E ":${WEB_PORT}\s" || echo "端口 ${WEB_PORT} 未监听"
}
