#!/bin/bash
#
# 复制修复代码并启动服务
#

set -e

echo "=========================================="
echo "🚀 Copying fixed code and starting service"
echo "=========================================="

# 杀死所有旧进程
echo "🔪 Killing old 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')
" 2>/dev/null || true

sleep 2

# 确保目录存在
mkdir -p /app/scripts
cd /app/scripts

# 启动修复后的RPC服务
echo "🚀 Starting fixed RPC on port 8008..."
python3 final_rpc_correct.py &
RPC_PID=$!
echo "RPC started with PID: $RPC_PID"

sleep 3

# 启动修复后的API服务
echo "🚀 Starting fixed API on port 8088..."
python3 -m uvicorn api_for_fixed_rpc:app --host 0.0.0.0 --port 8088 &
API_PID=$!
echo "API started with PID: $API_PID"

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

# 等待进程
wait
