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

import sys
import importlib
import types

class VnpyAppCompatibility:
    """vnpy.app 兼容性层"""
    
    def __init__(self):
        self._setup_compatibility()
    
    def _setup_compatibility(self):
        """设置兼容性层"""
        # 检查是否已经存在 vnpy.app
        if 'vnpy.app' in sys.modules:
            print("✅ vnpy.app 模块已存在")
            return
        
        print("🔧 创建 vnpy.app 兼容性层...")
        
        # 创建 vnpy.app 模块
        vnpy_app_module = types.ModuleType('vnpy.app')
        sys.modules['vnpy.app'] = vnpy_app_module
        
        # 创建 vnpy.app.cta_strategy 子模块
        cta_strategy_module = types.ModuleType('vnpy.app.cta_strategy')
        sys.modules['vnpy.app.cta_strategy'] = cta_strategy_module
        
        # 创建 vnpy.app.cta_backtester 子模块
        cta_backtester_module = types.ModuleType('vnpy.app.cta_backtester')
        sys.modules['vnpy.app.cta_backtester'] = cta_backtester_module
        
        # 创建 vnpy.app.data_manager 子模块
        data_manager_module = types.ModuleType('vnpy.app.data_manager')
        sys.modules['vnpy.app.data_manager'] = data_manager_module
        
        # 创建 vnpy.app.rpc_service 子模块
        rpc_service_module = types.ModuleType('vnpy.app.rpc_service')
        sys.modules['vnpy.app.rpc_service'] = rpc_service_module
        
        # 映射实际模块到兼容层
        self._map_modules(vnpy_app_module)
        
        print("✅ vnpy.app 兼容性层创建完成")
    
    def _map_modules(self, vnpy_app_module):
        """映射实际模块到兼容层"""
        # 映射 vnpy_ctastrategy -> vnpy.app.cta_strategy
        try:
            from vnpy_ctastrategy import CtaStrategyApp, CtaTemplate
            vnpy_app_module.CtaStrategyApp = CtaStrategyApp
            sys.modules['vnpy.app.cta_strategy'].CtaStrategyApp = CtaStrategyApp
            sys.modules['vnpy.app.cta_strategy'].CtaTemplate = CtaTemplate
            print("  ✅ 映射 CtaStrategyApp")
        except ImportError as e:
            print(f"  ⚠️  无法导入 vnpy_ctastrategy: {e}")
        
        # 映射 vnpy_ctabacktester -> vnpy.app.cta_backtester
        try:
            from vnpy_ctabacktester import CtaBacktesterApp
            vnpy_app_module.CtaBacktesterApp = CtaBacktesterApp
            sys.modules['vnpy.app.cta_backtester'].CtaBacktesterApp = CtaBacktesterApp
            print("  ✅ 映射 CtaBacktesterApp")
        except ImportError as e:
            print(f"  ⚠️  无法导入 vnpy_ctabacktester: {e}")
        
        # 映射 vnpy_datamanager -> vnpy.app.data_manager
        try:
            from vnpy_datamanager import DataManagerApp
            vnpy_app_module.DataManagerApp = DataManagerApp
            sys.modules['vnpy.app.data_manager'].DataManagerApp = DataManagerApp
            print("  ✅ 映射 DataManagerApp")
        except ImportError as e:
            print(f"  ⚠️  无法导入 vnpy_datamanager: {e}")
        
        # 映射 vnpy_webtrader -> vnpy.app.rpc_service (近似映射)
        try:
            from vnpy_webtrader import WebTraderApp
            vnpy_app_module.WebTraderApp = WebTraderApp
            sys.modules['vnpy.app.rpc_service'].WebTraderApp = WebTraderApp
            print("  ✅ 映射 WebTraderApp")
        except ImportError as e:
            print(f"  ⚠️  无法导入 vnpy_webtrader: {e}")
        
        # 映射其他常见类
        try:
            from vnpy.trader.engine import MainEngine
            vnpy_app_module.MainEngine = MainEngine
            print("  ✅ 映射 MainEngine")
        except ImportError as e:
            print(f"  ⚠️  无法导入 MainEngine: {e}")
        
        try:
            from vnpy.event import EventEngine
            vnpy_app_module.EventEngine = EventEngine
            print("  ✅ 映射 EventEngine")
        except ImportError as e:
            print(f"  ⚠️  无法导入 EventEngine: {e}")
    
    def test_import(self):
        """测试导入兼容性"""
        print("\n🧪 测试导入兼容性...")
        
        tests = [
            ("import vnpy.app", "vnpy.app"),
            ("from vnpy.app.cta_strategy import CtaStrategyApp", "CtaStrategyApp"),
            ("from vnpy.app.cta_backtester import CtaBacktesterApp", "CtaBacktesterApp"),
            ("from vnpy.app.data_manager import DataManagerApp", "DataManagerApp"),
        ]
        
        for import_stmt, expected in tests:
            try:
                exec(import_stmt)
                print(f"  ✅ {import_stmt}")
            except Exception as e:
                print(f"  ❌ {import_stmt}: {e}")

# 自动启用兼容性
compatibility = VnpyAppCompatibility()

if __name__ == "__main__":
    # 运行测试
    compatibility.test_import()
    
    # 显示可用的模块
    print("\n📦 可用的 vnpy.app 模块:")
    import vnpy.app
    for attr in dir(vnpy.app):
        if not attr.startswith('_'):
            print(f"  - {attr}")
    
    print("\n✅ vnpy.app 兼容性层已激活")
    print("现在可以正常导入 vnpy.app 相关模块了！")