#!/usr/bin/env python3
"""
重构NestedPage文件，让@Stable数据类真正被使用并移除timestamp字段
"""

import os
import re
from pathlib import Path

def refactor_nested_page(file_path):
    """重构单个NestedPage文件"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 移除timestamp字段和相关导入
        content = re.sub(r'import com\.dong\.maxhap\.utils\.getCurrentTimestamp\n?', '', content)
        content = re.sub(r'\s*val timestamp: Long = getCurrentTimestamp\(\),?\n?', '', content)
        
        # 查找所有@Stable数据类定义
        stable_class_pattern = r'@Stable\s+data class (\w+)\((.*?)\)(?:\s*@Stable\s+data class \w+\(.*?\))*'
        stable_classes = re.findall(stable_class_pattern, content, re.DOTALL)
        
        if not stable_classes:
            print(f"未找到@Stable类: {file_path}")
            return False
            
        # 提取页面编号
        page_num_match = re.search(r'NestedPage(\d+)', file_path.name)
        if not page_num_match:
            print(f"无法提取页面编号: {file_path}")
            return False
            
        page_num = int(page_num_match.group(1))
        
        # 在Composable函数中添加状态变量来使用这些@Stable数据
        composable_pattern = r'(@Composable\s+(?:internal\s+)?fun\s+NestedPage\d+\(\)\s*\{)'
        composable_match = re.search(composable_pattern, content)
        
        if not composable_match:
            print(f"未找到Composable函数: {file_path}")
            return False
            
        # 生成状态变量声明
        state_vars = []
        for i, (class_name, class_body) in enumerate(stable_classes[:4]):  # 只使用前4个类
            var_name = f"stableData{i+1}"
            state_vars.append(f"    val {var_name} by remember {{ mutableStateOf({class_name}()) }}")
        
        # 插入状态变量到Composable函数开头
        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中显示一些@Stable数据的信息
        ui_insertion_point = None
        
        # 找到Button之前的位置来插入数据显示
        button_pattern = r'(\s+Button\()'
        button_match = re.search(button_pattern, content)
        if button_match:
            ui_insertion_point = button_match.start()
        else:
            # 如果找不到Button，找Spacer
            spacer_pattern = r'(\s+Spacer\(modifier = Modifier\.height\()'
            spacer_match = re.search(spacer_pattern, content)
            if spacer_match:
                ui_insertion_point = spacer_match.start()
        
        if ui_insertion_point:
            # 生成UI显示代码
            display_code = []
            display_code.append("\n        // 显示@Stable数据信息")
            
            for i in range(min(3, len(stable_classes))):  # 显示前3个数据类的信息
                var_name = f"stableData{i+1}"
                class_name = stable_classes[i][0]
                
                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[:ui_insertion_point] + "\n".join(display_code) + content[ui_insertion_point:]
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
            
        print(f"重构完成: {file_path}")
        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
    processed_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 refactor_nested_page(file_path):
                    processed_files += 1
    
    print(f"\n处理完成!")
    print(f"总文件数: {total_files}")
    print(f"成功处理: {processed_files}")
    print(f"成功率: {processed_files/total_files*100:.1f}%" if total_files > 0 else "无文件需要处理")

if __name__ == "__main__":
    main()