#!/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"

start_app() {
  echo_info "正在启动 ${APP_NAME}..."

  local status
  status="$(supervisorctl status "${APP_NAME}" 2>/dev/null | awk '{print $2}' || echo "UNKNOWN")"

  if [[ "${status}" == "RUNNING" ]]; then
    echo_warn "${APP_NAME} 已在运行"
    supervisorctl status "${APP_NAME}"
    return 0
  fi

  supervisorctl start "${APP_NAME}"
  sleep 3

  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
  start_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 "$@"
