#!/usr/bin/env python3
"""
修复后的test_server.py
兼容vn.py 4.x版本
"""

import traceback
import zmq
import time
import sys
import os

# 添加vn.py路径
sys.path.insert(0, '/usr/local/lib/python3.10/site-packages')

def run_strategy_backtest(strategy_code: str, symbol: str, interval: str, start: int, end: int, **kwargs):
    """RPC方法：运行策略回测"""
    try:
        print(f"开始回测: {symbol} {start}-{end}")
        
        # 动态加载策略
        local_vars = {}
        exec(strategy_code, globals(), local_vars)
        
        # 查找CtaTemplate子类
        from vnpy_ctastrategy import CtaTemplate
        strategy_classes = [v for k, v in local_vars.items() 
                          if isinstance(v, type) and issubclass(v, CtaTemplate) and v != CtaTemplate]
        
        if not strategy_classes:
            return {"error": "策略代码中未找到CtaTemplate子类"}
        
        StrategyClass = strategy_classes[0]
        print(f"找到策略类: {StrategyClass.__name__}")
        
        # 创建事件引擎
        from vnpy.event import EventEngine
        event_engine = EventEngine()
        
        # 创建主引擎
        from vnpy.trader.engine import MainEngine
        main_engine = MainEngine(event_engine)
        
        # 添加回测引擎
        from vnpy_ctabacktester import BacktesterEngine
        backtester_engine = main_engine.add_app(BacktesterEngine, "backtester")
        
        # 设置回测参数
        setting = {
            "vt_symbol": symbol,
            "interval": interval,
            "start": start,
            "end": end,
            "rate": kwargs.get("rate", 0.00003),
            "slippage": kwargs.get("slippage", 0.2),
            "size": kwargs.get("size", 1),
            "pricetick": kwargs.get("pricetick", 0.2),
            "capital": kwargs.get("capital", 1000000),
        }
        
        print(f"回测参数: {setting}")
        
        # 运行回测
        backtester_engine.run_backtesting(
            strategy_class=StrategyClass,
            setting=setting
        )
        
        # 获取结果
        result = {
            "statistics": backtester_engine.get_statistics(),
            "result_df": backtester_engine.get_result_df().to_dict(orient="records"),
            "trades": backtester_engine.get_all_trades()
        }
        
        print(f"回测完成，统计项数: {len(result['statistics'])}")
        return result
        
    except Exception as e:
        error_info = {
            "error": str(e),
            "traceback": traceback.format_exc()
        }
        print(f"回测错误: {error_info}")
        return error_info

def main():
    """主函数"""
    print('🚀 启动修复后的WebTrader RPC服务...')
    
    # 创建ZMQ REP socket
    context = zmq.Context()
    rep_socket = context.socket(zmq.REP)
    rep_socket.bind("tcp://0.0.0.0:2014")
    
    print('✅ RPC服务已启动')
    print('   REP地址: tcp://0.0.0.0:2014')
    print('   外部访问: tcp://192.168.2.154:2014')
    print('   等待请求...')
    
    # 处理请求
    while True:
        try:
            # 接收请求
            req = rep_socket.recv_pyobj()
            print(f"收到请求: {req.get('function')}")
            
            function_name = req.get("function")
            args = req.get("args", [])
            kwargs = req.get("kwargs", {})
            
            if function_name == "run_strategy_backtest":
                result = run_strategy_backtest(*args, **kwargs)
            else:
                result = {"error": f"未知函数: {function_name}"}
            
            # 发送响应
            rep_socket.send_pyobj(result)
            print(f"请求处理完成")
            
        except Exception as e:
            error_result = {
                "error": str(e),
                "traceback": traceback.format_exc()
            }
            rep_socket.send_pyobj(error_result)
            print(f"处理请求时出错: {e}")

if __name__ == '__main__':
    main()