#!/usr/bin/env python3

import os
import re

def replace_system_current_time_in_file(file_path):
    """替换文件中的System.currentTimeMillis()为getCurrentTimestamp()"""
    
    # 读取原文件内容
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 检查是否包含System.currentTimeMillis()
    if 'System.currentTimeMillis()' in content:
        # 替换为getCurrentTimestamp()
        new_content = content.replace('System.currentTimeMillis()', 'getCurrentTimestamp()')
        
        # 添加导入语句（如果还没有的话）
        if 'import com.dong.maxhap.utils.getCurrentTimestamp' not in new_content:
            # 在package声明后添加导入
            package_match = re.search(r'^package\s+[^\n]+', new_content, re.MULTILINE)
            if package_match:
                insert_pos = package_match.end() + 1
                import_statement = 'import com.dong.maxhap.utils.getCurrentTimestamp\n'
                new_content = new_content[:insert_pos] + import_statement + new_content[insert_pos:]
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(new_content)
        
        return True
    return False

def process_all_nested_pages():
    """处理所有NestedPage文件"""
    base_dir = "/Users/dongsq/TestDemo/IR013/TestProject/MaxHap"
    lib_names = ["nestedlib1", "nestedlib2", "nestedlib3", "nestedlib4", "nestedlib5"]
    
    total_replaced = 0
    
    for lib_name in lib_names:
        lib_path = os.path.join(base_dir, lib_name, "src", "commonMain", "kotlin", "com", "dong", "maxhap", lib_name)
        
        if not os.path.exists(lib_path):
            print(f"目录不存在: {lib_path}")
            continue
            
        print(f"处理库: {lib_name}")
        
        # 获取所有NestedPage文件
        page_files = []
        for file_name in os.listdir(lib_path):
            if file_name.startswith("NestedPage") and file_name.endswith(".kt"):
                page_files.append(os.path.join(lib_path, file_name))
        
        for file_path in page_files:
            if replace_system_current_time_in_file(file_path):
                total_replaced += 1
                
                # 显示进度
                if total_replaced % 100 == 0:
                    print(f"  已处理 {total_replaced} 个文件")
    
    print(f"完成！总共替换了 {total_replaced} 个文件中的System.currentTimeMillis()调用。")

if __name__ == "__main__":
    process_all_nested_pages()