#!/usr/bin/env python3
"""
vn.py 4.x 兼容性修复脚本
"""

import os
import re

def fix_vnpy_imports(file_path):
    """修复文件中的vn.py导入"""
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 替换规则
    replacements = [
        (r'from vnpy\.app\.', 'from vnpy_'),
        (r'import vnpy\.app\.', 'import vnpy_'),
        (r'vnpy\.app\.cta_strategy', 'vnpy_ctastrategy'),
        (r'vnpy\.app\.cta_backtester', 'vnpy_ctabacktester'),
        (r'vnpy\.app\.data_manager', 'vnpy_datamanager'),
        (r'vnpy\.app\.rpc_service', 'vnpy_rpcservice'),
        (r'vnpy\.app\.algo_trading', 'vnpy_algotrading'),
    ]
    
    fixed_content = content
    for pattern, replacement in replacements:
        fixed_content = re.sub(pattern, replacement, fixed_content)
    
    if fixed_content != content:
        # 备份原文件
        backup_path = file_path + '.backup'
        os.rename(file_path, backup_path)
        
        # 写入修复后的文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(fixed_content)
        
        print(f"✅ 已修复: {file_path}")
        print(f"   备份: {backup_path}")
        return True
    else:
        print(f"✅ 无需修复: {file_path}")
        return False

# 使用示例
if __name__ == "__main__":
    # 修复当前目录下的Python文件
    for root, dirs, files in os.walk('.'):
        for file in files:
            if file.endswith('.py'):
                file_path = os.path.join(root, file)
                fix_vnpy_imports(file_path)
