#!/bin/bash
#
# 容器启动入口点 - 自动启动修复后的回测服务
#

echo "=========================================="
echo "🚀 Starting sanguo_vnpy with fixed backtest service"
echo "=========================================="

# 启动原有的supervisord
/usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf &

# 等待一会儿
sleep 5

# 杀死所有可能旧的回测进程
echo "🔪 Killing old backtest processes..."
python3 -c "
import os
import signal
count = 0
for proc in os.listdir('/proc'):
    if proc.isdigit():
        try:
            cmdline = open(f'/proc/{proc}/cmdline').read()
            if 'python' in cmdline and ('uvicorn' in cmdline or 'rpc' in cmdline or 'backtest' in cmdline or 'final_rpc' in cmdline):
                print(f'Killing pid {proc}: {cmdline[:60]}')
                os.kill(int(proc), signal.SIGKILL)
                count += 1
        except Exception as e:
            pass
print(f'Killed {count} processes')
"

sleep 2

# 启动修复后的服务
echo "🚀 Starting fixed backtest services..."
cd /app/scripts && python3 final_rpc_correct.py &
sleep 2
cd /app/scripts && python3 -m uvicorn api_for_fixed_rpc:app --host 0.0.0.0 --port 8088 &

echo "✅ All services started!"
echo "   RPC: 127.0.0.1:8008 (container internal)"
echo "   API: 0.0.0.0:8088 (host mapped)"
echo "=========================================="

# 等待所有进程
wait
