#!/bin/bash

# 为所有NestedPage文件添加@Stable元素的脚本

BASE_DIR="/Users/dongsq/TestDemo/IR013/TestProject/MaxHap"
LIB_NAMES=("nestedlib1" "nestedlib2" "nestedlib3" "nestedlib4" "nestedlib5")

echo "开始为NestedPage文件添加@Stable元素..."

# 为每个库处理文件
for lib_name in "${LIB_NAMES[@]}"; do
    LIB_DIR="$BASE_DIR/$lib_name/src/commonMain/kotlin/com/dong/maxhap/$lib_name"
    
    if [ ! -d "$LIB_DIR" ]; then
        echo "目录不存在: $LIB_DIR"
        continue
    fi
    
    echo "处理库: $lib_name"
    
    # 获取该库中的所有NestedPage文件
    PAGE_FILES=$(find "$LIB_DIR" -name "NestedPage*.kt" | sort -V)
    
    for file_path in $PAGE_FILES; do
        filename=$(basename "$file_path")
        page_number=$(echo "$filename" | sed 's/NestedPage\(.*\)\.kt/\1/')
        
        # 读取原文件内容
        ORIGINAL_CONTENT=$(cat "$file_path")
        
        # 生成8个@Stable数据类
        STABLE_CLASSES=""
        for i in {1..8}; do
            STABLE_CLASSES+="@Stable
data class StableData${page_number}_${i}(
    val id: Int = $((page_number * 1000 + i)),
    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 * 100 + i)),
    val description: String = \"Nested stable data for page ${page_number}, item ${i}\",
    val count: Int = ${i}00,
    val isEnabled: Boolean = ${i}%2==0
)

"
        done
        
        # 在imports后面插入@Stable类定义
        echo "$ORIGINAL_CONTENT" | awk -v stable_classes="$STABLE_CLASSES" '
        /^import / { 
            print $0
            found_import = 1
            next
        }
        found_import && !/^import / && !printed_stable {
            print ""
            print stable_classes
            printed_stable = 1
        }
        { print }
        ' > "${file_path}.tmp"
        
        # 替换原文件
        mv "${file_path}.tmp" "$file_path"
        
        # 显示进度
        if [ $((page_number % 50)) -eq 0 ]; then
            echo "  已处理 ${lib_name} 的第 ${page_number} 个页面"
        fi
    done
done

echo "完成！所有NestedPage文件已添加@Stable元素。"
echo "每个页面现在包含8个@Stable数据类。"