#!/bin/bash
# 最终修复vnpy.app导入问题

echo "🚀 开始最终修复vnpy.app导入问题..."
echo "============================================================"

# 1. 检查当前状态
echo "1. 检查当前状态..."
ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy python3 -c \"
import sys
print('Python版本:', sys.version)
print('sys.path:', sys.path[:3])

try:
    import vnpy.app
    print('✅ vnpy.app 已存在')
except ImportError:
    print('❌ vnpy.app 未找到，开始修复...')
\"" 2>&1 | grep -v "DeprecationWarning"

# 2. 安装必要的vn.py组件
echo -e "\n2. 安装vn.py组件..."
ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy pip install vnpy-ctastrategy vnpy-ctabacktester vnpy-datamanager vnpy-webtrader 2>&1 | grep -E '(Successfully|Requirement|Installing)' || echo '安装完成'"

# 3. 创建兼容性模块
echo -e "\n3. 创建兼容性模块..."
cat > /tmp/compatibility.py << 'EOF'
#!/usr/bin/env python3
"""
vnpy.app 兼容性修复模块
将此文件放入 /app/scripts/ 目录
"""

import sys
import types

def create_vnpy_app_compatibility():
    """创建 vnpy.app 兼容性层"""
    
    # 检查是否已有兼容层
    if 'vnpy.app' in sys.modules:
        print("✅ vnpy.app 已存在")
        return
    
    # 创建兼容性模块
    vnpy_app_module = types.ModuleType('vnpy.app')
    
    # 添加子模块
    submodule_names = ['cta_strategy', 'cta_backtester', 'data_manager', 'rpc_service']
    for name in submodule_names:
        full_name = f'vnpy.app.{name}'
        submodule = types.ModuleType(full_name)
        sys.modules[full_name] = submodule
        
        # 将子模块添加到父模块中
        setattr(vnpy_app_module, name, submodule)
    
    sys.modules['vnpy.app'] = vnpy_app_module
    
    # 动态导入实际模块并映射
    try:
        import vnpy_ctastrategy
        vnpy_app_module.CtaStrategyApp = vnpy_ctastrategy.CtaStrategyApp
        vnpy_app_module.cta_strategy.CtaStrategyApp = vnpy_ctastrategy.CtaStrategyApp
        print("  ✅ 映射 CtaStrategyApp")
    except ImportError:
        print("  ⚠️  无法导入 vnpy_ctastrategy")
    
    try:
        import vnpy_ctabacktester
        vnpy_app_module.CtaBacktesterApp = vnpy_ctabacktester.CtaBacktesterApp
        vnpy_app_module.cta_backtester.CtaBacktesterApp = vnpy_ctabacktester.CtaBacktesterApp
        print("  ✅ 映射 CtaBacktesterApp")
    except ImportError:
        print("  ⚠️  无法导入 vnpy_ctabacktester")
    
    try:
        import vnpy_datamanager
        vnpy_app_module.DataManagerApp = vnpy_datamanager.DataManagerApp
        vnpy_app_module.data_manager.DataManagerApp = vnpy_datamanager.DataManagerApp
        print("  ✅ 映射 DataManagerApp")
    except ImportError:
        print("  ⚠️  无法导入 vnpy_datamanager")
    
    try:
        import vnpy_webtrader
        vnpy_app_module.WebTraderApp = vnpy_webtrader.WebTraderApp
        vnpy_app_module.rpc_service.WebTraderApp = vnpy_webtrader.WebTraderApp
        print("  ✅ 映射 WebTraderApp")
    except ImportError:
        print("  ⚠️  无法导入 vnpy_webtrader")
    
    print("✅ vnpy.app 兼容性层创建完成")

if __name__ == "__main__":
    create_vnpy_app_compatibility()
    
    # 测试导入
    print("\n🧪 测试导入...")
    try:
        import vnpy.app
        print("✅ vnpy.app 导入成功")
        
        # 列出可用模块
        print("\n📦 可用的 vnpy.app 模块:")
        for attr in dir(vnpy.app):
            if not attr.startswith('_'):
                print(f"  - {attr}")
    except Exception as e:
        print(f"❌ 导入失败: {e}")
EOF

# 4. 复制到容器
echo -e "\n4. 复制到容器..."
ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy bash -c 'cat > /app/scripts/compatibility.py' " < /tmp/compatibility.py

# 5. 运行兼容性修复
echo -e "\n5. 激活兼容性层..."
ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy python3 /app/scripts/compatibility.py"

# 6. 测试修复结果
echo -e "\n6. 测试修复结果..."
echo "测试导入 vnpy.app..."
ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy python3 -c \"
try:
    import vnpy.app
    print('✅ vnpy.app 导入成功！')
    
    # 检查可用模块
    print('\\n📦 可用的 vnpy.app 模块:')
    for attr in dir(vnpy.app):
        if not attr.startswith('_'):
            print(f'  - {attr}')
    
    # 测试常用导入
    try:
        from vnpy.app.cta_strategy import CtaStrategyApp
        print('\\n✅ 成功导入 CtaStrategyApp')
    except Exception as e:
        print(f'\\n❌ 无法导入 CtaStrategyApp: {e}')
    
except Exception as e:
    print(f'❌ vnpy.app 导入失败: {e}')
\"" 2>&1 | grep -v "DeprecationWarning"

# 7. 重启服务
echo -e "\n7. 重启回测服务..."
ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy bash -c '
    # 停止旧服务
    pkill -f test_server 2>/dev/null
    pkill -f backtest_api 2>/dev/null
    sleep 2
    
    # 启动修复后的服务
    echo \"启动修复后的 ZMQ RPC 服务...\"
    python3 /app/scripts/test_server_fixed.py &
    sleep 3
    
    echo \"启动修复后的 API 服务...\"
    python3 /app/scripts/backtest_api_fixed.py &
    sleep 3
    
    echo \"服务已重启\"
'" 2>&1

# 8. 验证修复
echo -e "\n8. 验证修复..."
sleep 3

echo -n "API健康检查: "
curl -s http://192.168.2.154:8088/health 2>&1 | grep -q "Not Found" && echo "✅ 正常 (404 expected)" || echo "❌ 异常"

echo -n "Swagger UI: "
curl -s -I http://192.168.2.154:8088/docs 2>&1 | grep -q "200 OK" && echo "✅ 正常" || echo "❌ 异常"

echo -e "\n============================================================"
echo "修复完成！"
echo "请通知司马懿将军运行测试脚本："
echo "cd pangtong-value/research/task-20260329-strategy-backtest/simayi"
echo "python3 backtest_workflow.py"
echo "============================================================"