#!/usr/bin/env python3
"""
最终修复脚本：彻底解决@Stable数据类使用和编译问题
"""

import os
import re
from pathlib import Path

def final_fix_file(file_path):
    """对文件进行最终修复"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 1. 移除所有timestamp相关的内容
        content = re.sub(r'import com\.dong\.maxhap\.utils\.getCurrentTimestamp\n?', '', content)
        content = re.sub(r'\s*val timestamp: Long = getCurrentTimestamp\(\),?\n?', '', content)
        
        # 2. 修复字符串插值语法错误
        content = content.replace('{$', '${')
        
        # 3. 确保正确的@Stable数据类使用
        page_num_match = re.search(r'NestedPage(\d+)', file_path.name)
        if not page_num_match:
            return False
            
        page_num = page_num_match.group(1)
        
        # 4. 修复状态变量声明
        # 移除错误的状态变量声明
        content = re.sub(r'val stableData\d+ by remember \{ mutableStateOf\(NestedStableData\d+_\d+\(\)\) \}', '', content)
        
        # 在正确位置添加状态变量
        composable_pattern = r'(@Composable\s+(?:internal\s+)?fun\s+NestedPage\d+\(\)\s*\{)'
        composable_match = re.search(composable_pattern, content)
        
        if composable_match:
            # 添加正确的状态变量
            state_vars = [
                f"    var showNextPage by remember {{ mutableStateOf(false) }}",
                f"    val stableData1 by remember {{ mutableStateOf(StableData{page_num}_1()) }}",
                f"    val stableData2 by remember {{ mutableStateOf(StableData{page_num}_2()) }}",
                f"    val stableData3 by remember {{ mutableStateOf(StableData{page_num}_3()) }}",
                f"    val stableData4 by remember {{ mutableStateOf(StableData{page_num}_4()) }}",
                ""
            ]
            
            insert_pos = composable_match.end(1)
            content = content[:insert_pos] + "\n" + "\n".join(state_vars) + content[insert_pos:]
        
        # 5. 清理多余的空行
        content = re.sub(r'\n{3,}', '\n\n', content)
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
            
        return True
        
    except Exception as e:
        print(f"处理文件时出错 {file_path}: {e}")
        return False

def main():
    base_path = Path("/Users/dongsq/TestDemo/IR013/TestProject/MaxHap")
    nested_libs = ["nestedlib1", "nestedlib2", "nestedlib3", "nestedlib4", "nestedlib5"]
    
    total_files = 0
    fixed_files = 0
    
    for lib in nested_libs:
        lib_path = base_path / lib / "src/commonMain/kotlin/com/dong/maxhap" / lib
        if not lib_path.exists():
            continue
            
        # 处理该库中的所有NestedPage文件
        for file_path in lib_path.glob("NestedPage*.kt"):
            if file_path.is_file():
                total_files += 1
                if final_fix_file(file_path):
                    fixed_files += 1
    
    print(f"\n最终修复完成!")
    print(f"总文件数: {total_files}")
    print(f"成功修复: {fixed_files}")
    print(f"成功率: {fixed_files/total_files*100:.1f}%" if total_files > 0 else "无文件需要处理")

if __name__ == "__main__":
    main()