#!/usr/bin/env bash
# PM2 子代理入口:在策略目录(cwd)加载 .env 后启动 agent.py
set -e
set -o pipefail

HUB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
REPO_ROOT="$(cd "${HUB_DIR}/.." && pwd)"
export PYTHONPATH="${REPO_ROOT}${PYTHONPATH:+:${PYTHONPATH}}"
# shellcheck source=lib_load_dotenv.sh
source "${HUB_DIR}/scripts/lib_load_dotenv.sh"

VENV_PY="${HUB_DIR}/.venv/bin/python"
AGENT_PY="${HUB_DIR}/agent.py"

_PM2_EXCHANGE="${EXCHANGE:-}"
_PM2_PORT="${PORT:-}"
_PM2_HOST="${HOST:-}"

if [[ ! -x "${VENV_PY}" ]]; then
  echo "未找到 ${VENV_PY},请先在 manual_trading_hub: python3 -m venv .venv && pip install -r requirements.txt" >&2
  exit 1
fi

if [[ -f .env ]]; then
  if grep -q $'\r' .env 2>/dev/null; then
    echo "警告: $(pwd)/.env 含 Windows 换行(CRLF),请在仓库根执行: bash manual_trading_hub/scripts/fix_env_crlf.sh" >&2
  fi
  if ! load_dotenv_file ".env"; then
    echo "错误: $(pwd)/.env 加载失败" >&2
    exit 1
  fi
else
  echo "警告: $(pwd) 下无 .env,agent 可能缺少 API 密钥" >&2
fi

[[ -n "${_PM2_EXCHANGE}" ]] && export EXCHANGE="${_PM2_EXCHANGE}"
[[ -n "${_PM2_PORT}" ]] && export PORT="${_PM2_PORT}"
[[ -n "${_PM2_HOST}" ]] && export HOST="${_PM2_HOST}"

if command -v ss >/dev/null 2>&1 && [[ -n "${PORT:-}" ]]; then
  if ss -tln 2>/dev/null | grep -q ":${PORT} "; then
    echo "错误: 端口 ${PORT} 已被占用,agent 无法监听(exchange=${EXCHANGE:-?})" >&2
    exit 1
  fi
fi

echo "agent start: exchange=${EXCHANGE:-?} port=${PORT:-?} cwd=$(pwd)" >&2
exec "${VENV_PY}" "${AGENT_PY}"
