#!/usr/bin/env python3
"""
清理和重新组织NestedPage文件，确保@Stable数据类被正确使用
"""

import os
import re
from pathlib import Path

def cleanup_file(file_path):
    """清理单个文件"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 移除多余的空行
        content = re.sub(r'\n{3,}', '\n\n', content)
        
        # 修复状态变量声明的位置
        lines = content.split('\n')
        new_lines = []
        i = 0
        
        while i < len(lines):
            line = lines[i]
            
            # 如果找到Composable函数开始
            if '@Composable' in line and 'fun NestedPage' in line:
                new_lines.append(line)
                i += 1
                
                # 跳过直到找到var showNextPage声明
                while i < len(lines) and 'var showNextPage' not in lines[i]:
                    i += 1
                
                if i < len(lines):
                    # 添加状态变量声明
                    new_lines.append('    var showNextPage by remember { mutableStateOf(false) }')
                    new_lines.append('    val stableData1 by remember { mutableStateOf(StableDataXXX_1()) }')
                    new_lines.append('    val stableData2 by remember { mutableStateOf(StableDataXXX_2()) }')
                    new_lines.append('    val stableData3 by remember { mutableStateOf(StableDataXXX_3()) }')
                    new_lines.append('    val stableData4 by remember { mutableStateOf(StableDataXXX_4()) }')
                    new_lines.append('')
                    i += 1  # 跳过原来的var showNextPage行
            else:
                new_lines.append(line)
                i += 1
        
        content = '\n'.join(new_lines)
        
        # 替换XXX为实际的页面编号
        page_num_match = re.search(r'NestedPage(\d+)', file_path.name)
        if page_num_match:
            page_num = page_num_match.group(1)
            content = content.replace('StableDataXXX', f'StableData{page_num}')
        
        # 写回文件
        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
    cleaned_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 cleanup_file(file_path):
                    cleaned_files += 1
    
    print(f"\n清理完成!")
    print(f"总文件数: {total_files}")
    print(f"成功清理: {cleaned_files}")

if __name__ == "__main__":
    main()