#!/bin/bash

# 配置参数
BASE_DIR="/Users/dongsq/TestDemo/IR013/TestProject/MaxHap"
TOTAL_LIBS=5
FILES_PER_LIB=200
LIB_NAMES=("nestedlib1" "nestedlib2" "nestedlib3" "nestedlib4" "nestedlib5")

echo "开始生成最终的HAP测试文件..."

# 删除旧的库目录
for lib_name in "${LIB_NAMES[@]}"; do
    if [ -d "$BASE_DIR/$lib_name" ]; then
        rm -rf "$BASE_DIR/$lib_name"
        echo "删除旧库: $lib_name"
    fi
done

# 为每个库生成文件
for lib_index in "${!LIB_NAMES[@]}"; do
    lib_name="${LIB_NAMES[$lib_index]}"
    LIB_DIR="$BASE_DIR/$lib_name"
    
    # 创建目录结构
    mkdir -p "$LIB_DIR/src/commonMain/kotlin/com/dong/maxhap/$lib_name"
    echo "创建库目录: $LIB_DIR"
    
    # 生成200个文件
    echo "生成库 $lib_name 的文件..."
    
    for i in $(seq 1 $FILES_PER_LIB); do
        FILE_INDEX=$((lib_index * FILES_PER_LIB + i))
        FILENAME="NestedPage${FILE_INDEX}.kt"
        FILEPATH="$LIB_DIR/src/commonMain/kotlin/com/dong/maxhap/$lib_name/$FILENAME"
        FUNCTION_NAME="NestedPage${FILE_INDEX}"
        NEXT_PAGE_VAR="showNextPage${FILE_INDEX}"
        
        # 决定函数可见性：跨库调用的函数设为public
        if [ $FILE_INDEX -eq 201 ] || [ $FILE_INDEX -eq 401 ] || [ $FILE_INDEX -eq 601 ] || [ $FILE_INDEX -eq 801 ]; then
            VISIBILITY="fun"
        else
            VISIBILITY="internal fun"
        fi
        
        # 生成文件头部
        echo "package com.dong.maxhap.$lib_name" > "$FILEPATH"
        echo "" >> "$FILEPATH"
        echo "import androidx.compose.foundation.layout.*" >> "$FILEPATH"
        echo "import androidx.compose.material.*" >> "$FILEPATH"
        echo "import androidx.compose.runtime.*" >> "$FILEPATH"
        echo "import androidx.compose.ui.Alignment" >> "$FILEPATH"
        echo "import androidx.compose.ui.Modifier" >> "$FILEPATH"
        echo "import androidx.compose.ui.graphics.Color" >> "$FILEPATH"
        echo "import androidx.compose.ui.text.font.FontWeight" >> "$FILEPATH"
        echo "import androidx.compose.ui.unit.dp" >> "$FILEPATH"
        echo "import androidx.compose.ui.unit.sp" >> "$FILEPATH"
        echo "" >> "$FILEPATH"
        echo "@Composable" >> "$FILEPATH"
        echo "$VISIBILITY $FUNCTION_NAME() {" >> "$FILEPATH"
        echo "    var $NEXT_PAGE_VAR by remember { mutableStateOf(false) }" >> "$FILEPATH"
        echo "" >> "$FILEPATH"
        
        # 添加跨库调用逻辑
        if [ $FILE_INDEX -eq 200 ]; then
            echo "    if ($NEXT_PAGE_VAR) {" >> "$FILEPATH"
            echo "        com.dong.maxhap.nestedlib2.NestedPage201()" >> "$FILEPATH"
            echo "        return" >> "$FILEPATH"
            echo "    }" >> "$FILEPATH"
            echo "" >> "$FILEPATH"
        elif [ $FILE_INDEX -eq 400 ]; then
            echo "    if ($NEXT_PAGE_VAR) {" >> "$FILEPATH"
            echo "        com.dong.maxhap.nestedlib3.NestedPage401()" >> "$FILEPATH"
            echo "        return" >> "$FILEPATH"
            echo "    }" >> "$FILEPATH"
            echo "" >> "$FILEPATH"
        elif [ $FILE_INDEX -eq 600 ]; then
            echo "    if ($NEXT_PAGE_VAR) {" >> "$FILEPATH"
            echo "        com.dong.maxhap.nestedlib4.NestedPage601()" >> "$FILEPATH"
            echo "        return" >> "$FILEPATH"
            echo "    }" >> "$FILEPATH"
            echo "" >> "$FILEPATH"
        elif [ $FILE_INDEX -eq 800 ]; then
            echo "    if ($NEXT_PAGE_VAR) {" >> "$FILEPATH"
            echo "        com.dong.maxhap.nestedlib5.NestedPage801()" >> "$FILEPATH"
            echo "        return" >> "$FILEPATH"
            echo "    }" >> "$FILEPATH"
            echo "" >> "$FILEPATH"
        elif [ $FILE_INDEX -lt $((TOTAL_LIBS * FILES_PER_LIB)) ]; then
            echo "    if ($NEXT_PAGE_VAR) {" >> "$FILEPATH"
            echo "        NestedPage$((FILE_INDEX + 1))()" >> "$FILEPATH"
            echo "        return" >> "$FILEPATH"
            echo "    }" >> "$FILEPATH"
            echo "" >> "$FILEPATH"
        fi
        
        # 生成UI内容
        echo "    Column(" >> "$FILEPATH"
        echo "        modifier = Modifier" >> "$FILEPATH"
        echo "            .fillMaxSize()" >> "$FILEPATH"
        echo "            .padding(16.dp)," >> "$FILEPATH"
        echo "        horizontalAlignment = Alignment.CenterHorizontally," >> "$FILEPATH"
        echo "        verticalArrangement = Arrangement.Center" >> "$FILEPATH"
        echo "    ) {" >> "$FILEPATH"
        echo "        Text(" >> "$FILEPATH"
        echo "            text = \"第${FILE_INDEX}层页面 ($lib_name)\"," >> "$FILEPATH"
        echo "            fontSize = 24.sp," >> "$FILEPATH"
        echo "            fontWeight = FontWeight.Bold," >> "$FILEPATH"
        echo "            color = Color(0xFF$((lib_index * 50))0000)," >> "$FILEPATH"
        echo "            modifier = Modifier.padding(bottom = 20.dp)" >> "$FILEPATH"
        echo "        )" >> "$FILEPATH"
        
        # 生成文本内容
        for j in $(seq 1 10); do
            LINE_NUM=$(( (FILE_INDEX - 1) * 10 + j ))
            RED=$(( (LINE_NUM * 17) % 256 ))
            GREEN=$(( (LINE_NUM * 31) % 256 ))
            BLUE=$(( (LINE_NUM * 47) % 256 ))
            echo "        Text(" >> "$FILEPATH"
            echo "            text = \"这是第${LINE_NUM}行内容\"," >> "$FILEPATH"
            echo "            fontSize = 14.sp," >> "$FILEPATH"
            echo "            color = Color($RED, $GREEN, $BLUE)," >> "$FILEPATH"
            echo "            modifier = Modifier.padding(vertical = 3.dp)" >> "$FILEPATH"
            echo "        )" >> "$FILEPATH"
        done
        
        # 添加导航按钮
        if [ $FILE_INDEX -lt $((TOTAL_LIBS * FILES_PER_LIB)) ]; then
            echo "" >> "$FILEPATH"
            echo "        Spacer(modifier = Modifier.height(25.dp))" >> "$FILEPATH"
            echo "" >> "$FILEPATH"
            echo "        Button(" >> "$FILEPATH"
            echo "            onClick = { $NEXT_PAGE_VAR = true }," >> "$FILEPATH"
            echo "            modifier = Modifier" >> "$FILEPATH"
            echo "                .fillMaxWidth()" >> "$FILEPATH"
            echo "                .height(45.dp)," >> "$FILEPATH"
            echo "            colors = ButtonDefaults.buttonColors(" >> "$FILEPATH"
            echo "                backgroundColor = Color(0xFF2196F3)" >> "$FILEPATH"
            echo "            )" >> "$FILEPATH"
            echo "        ) {" >> "$FILEPATH"
            
            if [ $i -lt $FILES_PER_LIB ]; then
                echo "            Text(" >> "$FILEPATH"
                echo "                text = \"进入同库第$((FILE_INDEX + 1))层\"," >> "$FILEPATH"
                echo "                fontSize = 16.sp," >> "$FILEPATH"
                echo "                fontWeight = FontWeight.Medium," >> "$FILEPATH"
                echo "                color = Color.White" >> "$FILEPATH"
                echo "            )" >> "$FILEPATH"
            else
                if [ $lib_index -lt $((TOTAL_LIBS - 1)) ]; then
                    next_lib_display="${LIB_NAMES[$((lib_index + 1))]}"
                    echo "            Text(" >> "$FILEPATH"
                    echo "                text = \"进入${next_lib_display}第$((FILE_INDEX + 1))层\"," >> "$FILEPATH"
                    echo "                fontSize = 16.sp," >> "$FILEPATH"
                    echo "                fontWeight = FontWeight.Medium," >> "$FILEPATH"
                    echo "                color = Color.White" >> "$FILEPATH"
                    echo "            )" >> "$FILEPATH"
                else
                    echo "            Text(" >> "$FILEPATH"
                    echo "                text = \"已到达最深层\"," >> "$FILEPATH"
                    echo "                fontSize = 16.sp," >> "$FILEPATH"
                    echo "                fontWeight = FontWeight.Medium," >> "$FILEPATH"
                    echo "                color = Color.White" >> "$FILEPATH"
                    echo "            )" >> "$FILEPATH"
                fi
            fi
            echo "        }" >> "$FILEPATH"
        fi
        
        echo "    }" >> "$FILEPATH"
        echo "}" >> "$FILEPATH"
        
        # 显示进度
        if [ $((i % 50)) -eq 0 ]; then
            echo "  已生成库 $lib_name 的 $i 个文件"
        fi
    done
done

# 为每个库创建build.gradle.kts文件（参考composeApp配置）
for lib_index in "${!LIB_NAMES[@]}"; do
    lib_name="${LIB_NAMES[$lib_index]}"
    LIB_DIR="$BASE_DIR/$lib_name"
    
    cat > "$LIB_DIR/build.gradle.kts" << EOF
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
import org.jetbrains.kotlin.gradle.dsl.JvmTarget

plugins {
    kotlin("multiplatform")
    id("com.android.library")
    id("org.jetbrains.compose")
    id("org.jetbrains.kotlin.plugin.compose")
}

android {
    namespace = "com.dong.maxhap.$lib_name"
    compileSdk = 34
    
    defaultConfig {
        minSdk = 24
    }
    
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }
}

kotlin {
    androidTarget {
        @OptIn(ExperimentalKotlinGradlePluginApi::class)
        compilerOptions {
            jvmTarget.set(JvmTarget.JVM_11)
        }
    }
    
    listOf(
        iosX64(),
        iosArm64(),
        iosSimulatorArm64()
    ).forEach { iosTarget ->
        iosTarget.binaries.framework {
            baseName = "${lib_name^}"
            isStatic = true
        }
    }
    
    ohosArm64 {
        binaries.sharedLib {
            baseName = "$lib_name"
        }
        compilations.named("main") {
            compilerOptions.configure {
                freeCompilerArgs.addAll(
                    listOf(
                        "-Xinclude-library=org.jetbrains.kotlin.native.platform.kba_devices",
                        "-Xdisable-default-klib-resolution"
                    )
                )
            }
        }
    }
    
    sourceSets {
        androidMain.dependencies {
            implementation(libs.androidx.activity.compose)
            implementation(libs.androidx.collection)
            implementation(libs.androidx.lifecycle.viewmodelCompose)
            implementation(libs.androidx.lifecycle.runtimeCompose)
        }
        commonMain.dependencies {
            implementation(compose.runtime)
            implementation(compose.foundation)
            implementation(compose.material)
            implementation(compose.ui)
            implementation(compose.components.resources)
            implementation(compose.components.uiToolingPreview)
            implementation(libs.kotlinx.coroutines.core)
            implementation(libs.atomicFu)
EOF

    # 添加跨库依赖
    if [ $lib_index -lt $((TOTAL_LIBS - 1)) ]; then
        next_lib="${LIB_NAMES[$((lib_index + 1))]}"
        echo "            // 跨库依赖" >> "$LIB_DIR/build.gradle.kts"
        echo "            implementation(project(\":$next_lib\"))" >> "$LIB_DIR/build.gradle.kts"
    fi

    cat >> "$LIB_DIR/build.gradle.kts" << EOF
        }
        val ohosArm64Main by getting {
            dependencies {
                api(libs.compose.multiplatform.export)
            }
        }
    }
}

val versionCatalog = extensions.getByType<VersionCatalogsExtension>().named("libs")
val cmpVersion = versionCatalog.findVersion("composeMultiplatform")
    .orElseThrow { IllegalStateException("Missing version composeMultiplatform in version catalog") }
    .requiredVersion
val skikoOverrideByCmpVersion = mapOf(
    "1.9.2-ez-001" to "0.9.22.2-ez-001",
)
val skikoOhosOverride = skikoOverrideByCmpVersion[cmpVersion]

configurations.all {
    val configName = name
    if (configName.contains("ohos", ignoreCase = true)) {
        incoming.afterResolve {
            val resolvedSkiko = resolutionResult.allComponents
                .mapNotNull { it.moduleVersion }
                .firstOrNull { it.group == "org.jetbrains.skiko" && it.name == "skiko" }
            logger.lifecycle(
                "Resolved skiko for \$configName: " +
                        (resolvedSkiko?.let { "\${it.group}:\${it.name}:\${it.version}" } ?: "not found")
            )
        }
    }
    resolutionStrategy {
        eachDependency {
            if (requested.group == "org.jetbrains.skiko" && requested.name == "skiko") {
                if (configName.contains("ohos", ignoreCase = true)) {
                    skikoOhosOverride?.let { useVersion(it) }
                }
            }
            if (requested.group == "androidx.collection" && requested.name == "collection") {
                useVersion(libs.versions.androidx.collection.get())
            }
        }
    }
    exclude(group = "androidx.collection", module = "collection-jvm")
}
EOF
    
    echo "创建 $lib_name 的 build.gradle.kts"
done

# 更新settings.gradle.kts
SETTINGS_FILE="$BASE_DIR/settings.gradle.kts"
echo "" >> "$SETTINGS_FILE"
echo "// 嵌套页面库模块" >> "$SETTINGS_FILE"
for lib_name in "${LIB_NAMES[@]}"; do
    echo "include(\"$lib_name\")" >> "$SETTINGS_FILE"
done

echo ""
echo "成功生成5个嵌套页面库:"
echo "每个库包含200个文件，总共1000个嵌套页面"
echo "库列表: ${LIB_NAMES[*]}"
echo "请在composeApp的build.gradle.kts中添加依赖:"
echo ""
for lib_name in "${LIB_NAMES[@]}"; do
    echo "implementation(project(\":$lib_name\"))"
done