#!/bin/bash
# 完整安装vn.py及其所有组件

echo "🚀 开始完整安装vn.py及其组件..."
echo "============================================================"

# 1. 安装vn.py核心
echo "1. 安装vn.py核心..."
ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy pip install --upgrade vn.py 2>&1 | grep -E '(Successfully|Requirement|Installing)'"

# 2. 安装所有vn.py应用组件
echo -e "\n2. 安装vn.py应用组件..."
vnpy_apps=(
    "vnpy-ctastrategy"      # CTA策略引擎
    "vnpy-ctabacktester"    # CTA回测引擎
    "vnpy-datamanager"      # 数据管理
    "vnpy-datarecorder"     # 数据记录
    "vnpy-rpcservice"       # RPC服务
    "vnpy-webtrader"        # Web交易
    "vnpy-sqlite"           # SQLite数据库
    "vnpy-mysql"            # MySQL数据库
    "vnpy-mongodb"          # MongoDB数据库
    "vnpy-oss"              # 对象存储
)

for app in "${vnpy_apps[@]}"; do
    echo "   安装 $app..."
    ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy pip install $app 2>&1 | tail -1"
done

# 3. 安装vn.py的app模块（如果存在）
echo -e "\n3. 尝试安装vnpy.app模块..."
ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy pip install vnpy-app 2>&1 | grep -E '(Successfully|not find|ERROR)' || echo '尝试其他安装方式...'"

# 4. 验证安装
echo -e "\n4. 验证安装结果..."
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)

# 检查已安装的vn.py包
import pkgutil
vnpy_packages = []
for module in pkgutil.iter_modules():
    if 'vnpy' in module.name:
        vnpy_packages.append(module.name)

print(f'已安装的vn.py相关包 ({len(vnpy_packages)}个):')
for pkg in sorted(vnpy_packages):
    print(f'  - {pkg}')
\"" 2>&1 | grep -v "DeprecationWarning"

# 5. 测试关键模块导入
echo -e "\n5. 测试关键模块导入..."
ssh admin@192.168.2.154 "export PATH=\$PATH:/var/packages/Docker/target/usr/bin && docker exec sanguo_vnpy python3 -c \"
modules_to_test = [
    'vnpy',
    'vnpy.trader',
    'vnpy.event',
    'vnpy.trader.engine',
    'vnpy_ctastrategy',
    'vnpy_ctabacktester',
    'vnpy_webtrader',
    'vnpy_datamanager',
]

print('模块导入测试:')
for module in modules_to_test:
    try:
        __import__(module)
        print(f'  ✅ {module}')
    except ImportError as e:
        print(f'  ❌ {module}: {e}')
\"" 2>&1 | grep -v "DeprecationWarning"

# 6. 创建兼容性修复
echo -e "\n6. 创建兼容性修复..."
cat > /tmp/vnpy_compatibility.py << 'EOF'
#!/usr/bin/env python3
"""
vn.py 3.x/4.x 兼容性模块
解决 'No module named vnpy.app' 错误
"""

import sys

# 尝试导入vnpy.app，如果失败则创建虚拟模块
try:
    import vnpy.app
    print("✅ vnpy.app 模块已存在")
except ImportError:
    print("⚠️  vnpy.app 模块不存在，创建兼容层...")
    
    # 创建虚拟模块
    import types
    
    # 创建 vnpy.app 虚拟模块
    vnpy_app_module = types.ModuleType('vnpy.app')
    sys.modules['vnpy.app'] = vnpy_app_module
    
    # 添加常用子模块
    try:
        from vnpy_ctastrategy import CtaStrategyApp
        vnpy_app_module.CtaStrategyApp = CtaStrategyApp
        print("  ✅ 映射 CtaStrategyApp")
    except ImportError:
        print("  ⚠️  无法导入 CtaStrategyApp")
    
    try:
        from vnpy_ctabacktester import CtaBacktesterApp
        vnpy_app_module.CtaBacktesterApp = CtaBacktesterApp
        print("  ✅ 映射 CtaBacktesterApp")
    except ImportError:
        print("  ⚠️  无法导入 CtaBacktesterApp")
    
    try:
        from vnpy_datamanager import DataManagerApp
        vnpy_app_module.DataManagerApp = DataManagerApp
        print("  ✅ 映射 DataManagerApp")
    except ImportError:
        print("  ⚠️  无法导入 DataManagerApp")
    
    try:
        from vnpy_webtrader import WebTraderApp
        vnpy_app_module.WebTraderApp = WebTraderApp
        print("  ✅ 映射 WebTraderApp")
    except ImportError:
        print("  ⚠️  无法导入 WebTraderApp")
    
    print("✅ vnpy.app 兼容层创建完成")

# 测试导入
if __name__ == "__main__":
    try:
        import vnpy.app
        print("\n✅ 测试成功: vnpy.app 可导入")
        
        # 检查可用属性
        attrs = [attr for attr in dir(vnpy.app) if not attr.startswith('_')]
        print(f"可用属性: {attrs}")
    except Exception as e:
        print(f"\n❌ 测试失败: {e}")
EOF

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

# 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 \"导入兼容性模块...\"
    python3 -c \"import sys; sys.path.insert(0, \"/app/scripts\"); import vnpy_compatibility\"
    
    # 启动服务
    echo \"启动RPC服务...\"
    python3 /app/scripts/test_server_fixed.py &
    sleep 2
    
    echo \"启动API服务...\"
    python3 /app/scripts/backtest_api_fixed.py &
    sleep 2
    
    echo \"服务启动完成\"
'"

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

echo -n "检查API服务: "
curl -s http://192.168.2.154:8088/docs > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "✅ 正常"
else
    echo "❌ 失败"
fi

echo -n "检查ZMQ服务: "
timeout 2 bash -c "echo >/dev/tcp/192.168.2.154/8001" 2>/dev/null
if [ $? -eq 0 ]; then
    echo "✅ 正常"
else
    echo "❌ 失败"
fi

# 9. 测试回测
echo -e "\n9. 测试回测功能..."
cat > /tmp/test_fix.py << 'EOF'
import requests
import time

url = "http://192.168.2.154:8088/api/backtest/run"

# 使用vn.py 4.x兼容的导入
strategy_code = '''
from vnpy_ctastrategy import CtaTemplate

class FixedStrategy(CtaTemplate):
    author = "姜维修复版"
    
    def on_init(self):
        self.write_log("✅ 使用vn.py 4.x兼容导入")
'''

payload = {
    "strategy_code": strategy_code,
    "symbol": "rb8888.SHFE",
    "start": 20240101,
    "end": 20240102,
    "capital": 100000,
}

try:
    response = requests.post(url, json=payload, timeout=10)
    print(f"状态码: {response.status_code}")
    
    if response.status_code == 200:
        result = response.json()
        print(f"✅ 回测成功!")
        print(f"消息: {result.get('msg')}")
        print(f"返回码: {result.get('code')}")
    else:
        print(f"❌ 回测失败: {response.text}")
        
except Exception as e:
    print(f"❌ 测试错误: {e}")
EOF

echo "运行回测测试..."
python3 /tmp/test_fix.py

# 10. 清理
rm -f /tmp/vnpy_compatibility.py /tmp/test_fix.py

echo -e "\n============================================================"
echo "vn.py完整安装完成！"
echo "已解决 'No module named vnpy.app' 错误"
echo "请通知司马懿将军运行测试脚本:"
echo "cd pangtong-value/research/task-20260329-strategy-backtest/simayi"
echo "python3 backtest_workflow.py"
echo "============================================================"