#!/usr/bin/env python3
"""
在容器内清理占用端口的进程
"""

import subprocess
import sys

def main():
    """主函数"""
    print("🧹 在容器内清理占用端口的进程...")
    print("="*60)
    
    # 使用Python在容器内检测并关闭进程
    script = '''
import psutil
import socket

def get_pid_using_port(port):
    """获取占用指定端口的PID"""
    for conn in psutil.net_connections():
        if conn.laddr.port == port:
            return conn.pid
    return None

ports = [8001, 8088]
for port in ports:
    pid = get_pid_using_port(port)
    if pid:
        print(f"✅ 端口 {port} 被PID {pid} 占用，正在杀死...")
        try:
            process = psutil.Process(pid)
            process.terminate()
            process.wait(timeout=3)
            print(f"   ✅ 已杀死PID {pid}")
        except Exception as e:
            print(f"   ⚠️  杀死PID {pid} 失败: {e}")
    else:
        print(f"✅ 端口 {port} 未被占用")

print("\\n🧹 清理完成，现在启动新服务...")
'''
    
    # 执行清理脚本
    cmd = f'''ssh admin@192.168.2.154 "export PATH=$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy python3 -c '{script}'"'''
    print(f"执行清理...")
    subprocess.run(cmd, shell=True)
    
    print("\n🚀 启动新服务...")
    
    # 启动RPC服务
    rpc_cmd = f'''ssh admin@192.168.2.154 "export PATH=$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy bash -c 'python3 /app/scripts/test_server_final_fixed.py &'"'''
    subprocess.run(rpc_cmd, shell=True)
    
    # 等待
    import time
    time.sleep(3)
    
    # 启动API服务
    api_cmd = f'''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_fixed:app --host 0.0.0.0 --port 8088 &'"'''
    subprocess.run(api_cmd, shell=True)
    
    time.sleep(3)
    
    print("\n" + "="*60)
    print("✅ 清理和重启完成！")
    print("请测试回测API...")
    print("="*60)

if __name__ == "__main__":
    main()