#!/usr/bin/env bash
#
# DataOps Platform 重启脚本（Supervisor + dataops.env）
#

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# shellcheck source=dataops-common.sh
source "${SCRIPT_DIR}/dataops-common.sh"

restart_app() {
  echo_info "正在重启 ${APP_NAME}..."
  supervisorctl restart "${APP_NAME}"
  sleep 8

  local status
  status="$(supervisorctl status "${APP_NAME}" | awk '{print $2}')"
  if [[ "${status}" == "RUNNING" ]]; then
    echo_info "${APP_NAME} 重启成功"
    supervisorctl status "${APP_NAME}"
  else
    echo_error "${APP_NAME} 重启失败，状态: ${status}"
    echo_info "查看日志: tail -f ${SUPERVISOR_LOG}"
    exit 1
  fi
}

main() {
  echo "=========================================="
  echo "  DataOps Platform 重启脚本"
  echo "=========================================="

  if [[ "${EUID}" -ne 0 ]]; then
    echo_error "请使用 sudo 运行此脚本"
    exit 1
  fi

  check_env_file
  load_env_file
  check_venv
  check_run_script
  check_supervisor
  ensure_gunicorn_config "${SCRIPT_DIR}"
  ensure_run_script
  configure_supervisor
  restart_app
  if ! health_check; then
    echo_error "重启完成但服务未就绪，请查看上方诊断日志"
    exit 1
  fi

  local app_port
  app_port="$(resolve_listen_port)"
  echo ""
  echo_info "重启完成"
  echo_info "访问: http://127.0.0.1:${app_port}/api/system/health"
}

main "$@"
