/**
 * PM2:中控 hub + 三路子代理 agent(一次启动全部)
 *
 * 前置:
 *   cd manual_trading_hub
 *   source .venv/bin/activate && pip install -r requirements.txt
 *   cp .env.example .env
 *
 * 启动(hub + 全部 agent):
 *   pm2 start ecosystem.config.cjs
 *   pm2 save && pm2 startup
 *
 * 仅中控:pm2 start ecosystem.config.cjs --only manual-trading-hub
 * 仅某 agent:pm2 start ecosystem.config.cjs --only manual-agent-binance
 *
 * 快捷:bash scripts/pm2_hub.sh start
 */
const path = require("path");

const HUB_DIR = __dirname;
const REPO_ROOT = path.join(HUB_DIR, "..");
const RUN_HUB = path.join(HUB_DIR, "scripts", "run_hub.sh");
const RUN_AGENT = path.join(HUB_DIR, "scripts", "run_agent.sh");

function agentApp(name, exchangeDir, exchange, port) {
  return {
    name,
    cwd: path.join(REPO_ROOT, exchangeDir),
    script: RUN_AGENT,
    interpreter: "bash",
    instances: 1,
    autorestart: true,
    watch: false,
    max_memory_restart: "400M",
    restart_delay: 3000,
    max_restarts: 15,
    merge_logs: true,
    env: {
      EXCHANGE: exchange,
      PORT: String(port),
      HOST: "127.0.0.1",
      PYTHONPATH: REPO_ROOT,
    },
  };
}

module.exports = {
  apps: [
    agentApp("manual-agent-binance", "crypto_monitor_binance", "binance", 15200),
    agentApp("manual-agent-okx", "crypto_monitor_okx", "okx", 15201),
    agentApp("manual-agent-gate", "crypto_monitor_gate", "gate", 15202),
    {
      name: "manual-trading-hub",
      cwd: HUB_DIR,
      script: RUN_HUB,
      interpreter: "bash",
      instances: 1,
      autorestart: true,
      watch: false,
      max_memory_restart: "512M",
      env: {
        PYTHONPATH: REPO_ROOT,
      },
    },
  ],
};
