#!/usr/bin/env python3
"""
强制重启所有服务，确保加载最新代码
"""

import subprocess
import sys
import time

def main():
    print("🚀 强制重启所有服务，加载最新修正代码")
    print("="*60)
    
    # 杀死所有python进程
    print("🔪 杀死所有旧进程...")
    cmd = '''ssh admin@192.168.2.154 "export PATH=\\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy python3 -c '
import os
import signal
for proc in os.listdir("/proc"):
    if proc.isdigit():
        try:
            cmdline = open(f"/proc/{proc}/cmdline").read()
            if "test_server" in cmdline or "python" in cmdline and ("zmq" in cmdline or "8003" in cmdline):
                print(f"Killing {proc}: {cmdline[:60]}")
                os.kill(int(proc), signal.SIGKILL)
        except:
            pass
'
'''
    subprocess.run(cmd, shell=True)
    time.sleep(3)
    
    # 启动RPC服务
    print("\\n🚀 启动RPC服务（修正后版本）...")
    cmd = '''ssh admin@192.168.2.154 "export PATH=\\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy bash -c 'cd /app/scripts && python3 test_server_final_correct.py &'"'''
    subprocess.run(cmd, shell=True)
    time.sleep(3)
    
    # 检查RPC是否启动
    print("\\n🔍 检查RPC是否启动...")
    cmd = '''ssh admin@192.168.2.154 "export PATH=\\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy python3 -c '
import psutil
for conn in psutil.net_connections():
    if conn.laddr.port == 8003:
        print(f"✅ RPC running on port 8003, pid={conn.pid}")
'
'''
    subprocess.run(cmd, shell=True)
    
    # 启动API服务
    print("\\n🚀 启动API服务（端口8090）...")
    cmd = '''ssh admin@192.168.2.154 "export PATH=\\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy bash -c 'cd /app/scripts && python3 -m uvicorn backtest_api_final_correct_8090:app --host 0.0.0.0 --port 8090 &'"'''
    subprocess.run(cmd, shell=True)
    time.sleep(3)
    
    # 检查API是否启动
    print("\\n🔍 检查API是否启动...")
    cmd = '''ssh admin@192.168.2.154 "export PATH=\\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy python3 -c '
import psutil
for conn in psutil.net_connections():
    if conn.laddr.port == 8090:
        print(f"✅ API running on port 8090, pid={conn.pid}")
'
'''
    subprocess.run(cmd, shell=True)
    
    print("\\n" + "="*60)
    print("✅ 强制重启完成！")
    print("最终确认代码:")
    print("   backtester_engine = BacktesterEngine(main_engine, event_engine)")
    print("   main_engine.add_app(backtester_engine)")
    print("="*60)
    print("\\n🎯 API地址: http://192.168.2.154:8090/api/backtest/run")
    print("可以开始测试了！")

if __name__ == "__main__":
    main()
