#!/usr/bin/env python3
"""
创建 vnpy.app 兼容性模块
解决 vn.py 4.x 中缺少 vnpy.app 模块的问题
"""

import sys
import os
import types

def create_vnpy_app_module():
    """创建 vnpy.app 模块"""
    
    # 检查是否已存在
    if 'vnpy.app' in sys.modules:
        print("✅ vnpy.app 模块已存在")
        return
    
    print("🔧 创建 vnpy.app 兼容性模块...")
    
    # 创建 vnpy.app 顶级模块
    vnpy_app = types.ModuleType('vnpy.app')
    sys.modules['vnpy.app'] = vnpy_app
    
    # 创建子模块
    submodules = ['cta_strategy', 'cta_backtester', 'data_manager', 'rpc_service']
    
    for submodule_name in submodules:
        full_name = f'vnpy.app.{submodule_name}'
        submodule = types.ModuleType(full_name)
        sys.modules[full_name] = submodule
        setattr(vnpy_app, submodule_name, submodule)
        print(f"  ✅ 创建子模块: {full_name}")
    
    # 从实际模块导入并映射
    try:
        from vnpy_ctastrategy import CtaTemplate, CtaStrategyApp
        sys.modules['vnpy.app.cta_strategy'].CtaTemplate = CtaTemplate
        sys.modules['vnpy.app.cta_strategy'].CtaStrategyApp = CtaStrategyApp
        vnpy_app.CtaTemplate = CtaTemplate
        vnpy_app.CtaStrategyApp = CtaStrategyApp
        print("  ✅ 映射: CtaTemplate, CtaStrategyApp")
    except ImportError as e:
        print(f"  ❌ 无法导入 vnpy_ctastrategy: {e}")
    
    try:
        from vnpy_ctabacktester import CtaBacktesterApp
        sys.modules['vnpy.app.cta_backtester'].CtaBacktesterApp = CtaBacktesterApp
        vnpy_app.CtaBacktesterApp = CtaBacktesterApp
        print("  ✅ 映射: CtaBacktesterApp")
    except ImportError as e:
        print(f"  ❌ 无法导入 vnpy_ctabacktester: {e}")
    
    try:
        from vnpy_datamanager import DataManagerApp
        sys.modules['vnpy.app.data_manager'].DataManagerApp = DataManagerApp
        vnpy_app.DataManagerApp = DataManagerApp
        print("  ✅ 映射: DataManagerApp")
    except ImportError as e:
        print(f"  ❌ 无法导入 vnpy_datamanager: {e}")
    
    try:
        from vnpy_webtrader import WebTraderApp
        sys.modules['vnpy.app.rpc_service'].WebTraderApp = WebTraderApp
        vnpy_app.WebTraderApp = WebTraderApp
        print("  ✅ 映射: WebTraderApp")
    except ImportError as e:
        print(f"  ❌ 无法导入 vnpy_webtrader: {e}")
    
    # 添加其他常用模块
    try:
        from vnpy.trader.engine import MainEngine
        vnpy_app.MainEngine = MainEngine
        print("  ✅ 映射: MainEngine")
    except ImportError as e:
        print(f"  ❌ 无法导入 MainEngine: {e}")
    
    try:
        from vnpy.event import EventEngine
        vnpy_app.EventEngine = EventEngine
        print("  ✅ 映射: EventEngine")
    except ImportError as e:
        print(f"  ❌ 无法导入 EventEngine: {e}")
    
    print("✅ vnpy.app 兼容性模块创建完成")

def test_imports():
    """测试导入"""
    print("\n🧪 测试导入...")
    
    test_cases = [
        ("import vnpy.app", None),
        ("from vnpy.app.cta_strategy import CtaTemplate", "CtaTemplate"),
        ("from vnpy.app.cta_strategy import CtaStrategyApp", "CtaStrategyApp"),
        ("from vnpy.app.cta_backtester import CtaBacktesterApp", "CtaBacktesterApp"),
    ]
    
    for import_stmt, expected in test_cases:
        try:
            exec(import_stmt)
            if expected:
                print(f"  ✅ {import_stmt} -> {expected}")
            else:
                print(f"  ✅ {import_stmt}")
        except Exception as e:
            print(f"  ❌ {import_stmt}: {e}")

def main():
    """主函数"""
    print("🚀 创建 vnpy.app 兼容性模块")
    print("=" * 60)
    
    # 创建模块
    create_vnpy_app_module()
    
    # 测试导入
    test_imports()
    
    # 显示可用模块
    print("\n📦 可用的 vnpy.app 模块:")
    try:
        import vnpy.app
        for attr in dir(vnpy.app):
            if not attr.startswith('_'):
                print(f"  - {attr}")
    except Exception as e:
        print(f"  ❌ 无法导入 vnpy.app: {e}")
    
    print("\n✅ 兼容性模块创建完成！")
    print("现在可以正常使用 'from vnpy.app.cta_strategy import CtaTemplate' 了")

if __name__ == "__main__":
    main()