#!/usr/bin/env python3
"""
修复@Stable数据类的使用，确保它们被正确引用和显示
"""

import os
import re
from pathlib import Path

def fix_stable_usage(file_path):
    """修复单个文件中的@Stable数据类使用"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 检查是否已经有状态变量（避免重复添加）
        if 'val stableData' in content:
            return True
            
        # 查找@Stable数据类定义
        stable_classes = re.findall(r'@Stable\s+data class (\w+)\(', content)
        
        if not stable_classes:
            return False
            
        # 在Composable函数中添加状态变量
        composable_pattern = r'(@Composable\s+(?:internal\s+)?fun\s+NestedPage\d+\(\)\s*\{)'
        composable_match = re.search(composable_pattern, content)
        
        if not composable_match:
            return False
            
        # 生成状态变量声明（只使用前4个类）
        state_vars = []
        for i, class_name in enumerate(stable_classes[:4]):
            var_name = f"stableData{i+1}"
            state_vars.append(f"    val {var_name} by remember {{ mutableStateOf({class_name}()) }}")
        
        if not state_vars:
            return False
            
        # 插入状态变量
        insert_pos = composable_match.end(1)
        state_declaration = "\n" + "\n".join(state_vars) + "\n\n"
        content = content[:insert_pos] + state_declaration + content[insert_pos:]
        
        # 在UI中添加数据显示（在Spacer之前）
        spacer_pattern = r'(\s+Spacer\(modifier = Modifier\.height\()'
        spacer_match = re.search(spacer_pattern, content)
        
        if spacer_match:
            display_code = ["\n        // 显示@Stable数据信息"]
            
            for i in range(min(3, len(stable_classes))):
                var_name = f"stableData{i+1}"
                class_name = stable_classes[i]
                
                display_code.append(f"        Text(")
                display_code.append(f"            text = \"{class_name}: ID={{${var_name}.id}}, Name={{${var_name}.name}}\",")
                display_code.append(f"            fontSize = 12.sp,")
                display_code.append(f"            color = Color.Gray,")
                display_code.append(f"            modifier = Modifier.padding(vertical = 2.dp)")
                display_code.append(f"        )")
            
            display_code.append("")
            content = content[:spacer_match.start()] + "\n".join(display_code) + content[spacer_match.start():]
        
        # 写回文件
        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 fix_stable_usage(file_path):
                    fixed_files += 1
                else:
                    print(f"跳过文件（无需修改或出错）: {file_path}")
    
    print(f"\n修复完成!")
    print(f"总文件数: {total_files}")
    print(f"成功修复: {fixed_files}")

if __name__ == "__main__":
    main()