#!/usr/bin/env python3

import os
import re

def add_stable_elements_to_file(file_path, page_number):
    """为指定的NestedPage文件添加@Stable元素"""
    
    # 读取原文件内容
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 在imports部分后插入Stable imports
    import_section = '''import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.runtime.Stable'''
    
    # 生成8个@Stable数据类
    stable_classes = []
    
    for i in range(1, 9):
        stable_class = f'''@Stable
data class StableData{page_number}_{i}(
    val id: Int = {page_number}{i:03d},
    val name: String = "Stable_{page_number}_{i}",
    val value: Double = {page_number}.{i},
    val isActive: Boolean = true,
    val timestamp: Long = System.currentTimeMillis(),
    val tags: List<String> = listOf("tag1", "tag2", "tag3"),
    val metadata: Map<String, String> = mapOf("key1" to "value1", "key2" to "value2"),
    val nestedData: NestedStableData{page_number}_{i}? = null
)

@Stable
data class NestedStableData{page_number}_{i}(
    val subId: Int = {page_number}{i:02d},
    val description: String = "Nested stable data for page {page_number}, item {i}",
    val count: Int = {i}00,
    val isEnabled: Boolean = {'true' if i % 2 == 0 else 'false'}
)
'''
        stable_classes.append(stable_class)
    
    # 组合所有Stable类
    stable_section = '\n'.join(stable_classes)
    
    # 查找@Composable函数的位置
    composable_match = re.search(r'(@Composable\s+internal\s+fun\s+NestedPage\d+\(\)\s*{)', content)
    
    if composable_match:
        # 在@Composable函数前插入Stable类定义
        insert_pos = composable_match.start()
        new_content = content[:insert_pos] + stable_section + '\n' + content[insert_pos:]
    else:
        # 如果没找到@Composable，就在文件末尾添加
        new_content = content.rstrip() + '\n\n' + stable_section
    
    # 写回文件
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(new_content)

def process_all_nested_pages():
    """处理所有NestedPage文件"""
    base_dir = "/Users/dongsq/TestDemo/IR013/TestProject/MaxHap"
    lib_names = ["nestedlib1", "nestedlib2", "nestedlib3", "nestedlib4", "nestedlib5"]
    
    total_processed = 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(file_name)
        
        page_files.sort(key=lambda x: int(re.search(r'NestedPage(\d+)\.kt', x).group(1)))
        
        for file_name in page_files:
            file_path = os.path.join(lib_path, file_name)
            page_number_match = re.search(r'NestedPage(\d+)\.kt', file_name)
            
            if page_number_match:
                page_number = int(page_number_match.group(1))
                add_stable_elements_to_file(file_path, page_number)
                total_processed += 1
                
                if total_processed % 100 == 0:
                    print(f"  已处理 {total_processed} 个文件")
    
    print(f"完成！总共处理了 {total_processed} 个NestedPage文件。")
    print("每个页面现在包含8个@Stable数据类。")

if __name__ == "__main__":
    process_all_nested_pages()