
import android.databinding.tool.ext.capitalizeUS
import org.gradle.api.file.DuplicatesStrategy
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
import org.jetbrains.kotlin.gradle.dsl.JvmTarget

plugins {
    alias(libs.plugins.kotlinMultiplatform)
    alias(libs.plugins.androidApplication)
    alias(libs.plugins.composeMultiplatform)
    alias(libs.plugins.composeCompiler)
    // 开启 kotlinx.serialization（用于 navigation 类型安全路由）
    alias(libs.plugins.kotlinSerialization)
}

kotlin {
    androidTarget {
        @OptIn(ExperimentalKotlinGradlePluginApi::class) 
        compilerOptions {
            jvmTarget.set(JvmTarget.JVM_11)    
        }
    }

    listOf(
        iosX64(),      
        iosArm64(),    
        iosSimulatorArm64()
    ).forEach { iosTarget ->
        iosTarget.binaries.framework {
            baseName = "ComposeApp" 
            isStatic = true         
        }
        iosTarget.compilations.getByName("main") {
            compilerOptions.configure {
                freeCompilerArgs.add("-Xbinary=sanitizer=address")
            }
        }
    }
    

    ohosArm64 {
        binaries.sharedLib {
            baseName = "kn" // 共享库名称为kn
            export(libs.compose.multiplatform.export) // 导出compose多平台库的接口
             // 确保链接系统 zlib，使 libkn.so 的 NEEDED 包含 libz.so
            linkerOpts("-lz") 
        }
        val main by compilations.getting  
        main.compilerOptions.configure {
          //  freeCompilerArgs.add("-Xbinary=sanitizer=address")
        }
        val resource by main.cinterops.creating {
            defFile(file("src/ohosArm64Main/cinterop/resource.def"))        
            includeDirs(file("src/ohosArm64Main/cinterop/include"))        
        }
    }

    ohosX64 {
        binaries.sharedLib {
            baseName = "kn"
            export(libs.compose.multiplatform.export)
            linkerOpts("-lz")
        }
        val main by compilations.getting
        main.compilerOptions.configure {
         //   freeCompilerArgs.add("-Xbinary=sanitizer=address")
        }
        val resource by main.cinterops.creating {
            defFile(file("src/ohosX64Main/cinterop/resource.def"))
            includeDirs(file("src/ohosX64Main/cinterop/include"))
        }
    }

    sourceSets {
        androidMain.dependencies {
            implementation(libs.androidx.activity.compose)
            implementation(libs.androidx.lifecycle.viewmodelCompose)
            implementation(libs.androidx.lifecycle.runtimeCompose)
            implementation(libs.androidx.collection)   
            implementation(libs.compose.ui.backhandler) //需要单独依赖
            implementation(project(":lib-01"))
            implementation(project(":lib-02"))
            implementation(project(":lib-03"))
            implementation(project(":lib-04"))
            implementation(project(":lib-05"))
            implementation(project(":lib-06"))
            implementation(project(":lib-07"))
            implementation(project(":lib-08"))
            implementation(project(":lib-09"))
            implementation(project(":lib-10"))
            implementation(project(":lib-11"))
            implementation(project(":lib-12"))
            implementation(project(":lib-13"))
            implementation(project(":lib-14"))
            implementation(project(":lib-15"))
            implementation(project(":lib-16"))
            implementation(project(":lib-17"))
            implementation(project(":lib-18"))
            implementation(project(":lib-19"))
            implementation(project(":lib-20"))
        }
        commonMain.dependencies {
            implementation(compose.runtime)                       
            implementation(compose.foundation)                    
            implementation(compose.material)                      
            implementation(compose.material3)
            implementation(compose.ui)                            
            implementation(compose.components.resources)          
            implementation(compose.components.uiToolingPreview)   
            implementation(libs.kotlinx.coroutines.core)          
            implementation(libs.atomicFu)      
            implementation(libs.compose.navigation)
            // lib-01..lib-20 仅 Android/OHOS，不放在 commonMain，避免 appleMain 解析失败
        }

        val ohosArm64Main by getting {
            dependencies {
                api(libs.compose.multiplatform.export)
                implementation("org.jetbrains.skiko:skiko-ohosarm64")
                implementation(project(":lib-01"))
                implementation(project(":lib-02"))
                implementation(project(":lib-03"))
                implementation(project(":lib-04"))
                implementation(project(":lib-05"))
                implementation(project(":lib-06"))
                implementation(project(":lib-07"))
                implementation(project(":lib-08"))
                implementation(project(":lib-09"))
                implementation(project(":lib-10"))
                implementation(project(":lib-11"))
                implementation(project(":lib-12"))
                implementation(project(":lib-13"))
                implementation(project(":lib-14"))
                implementation(project(":lib-15"))
                implementation(project(":lib-16"))
                implementation(project(":lib-17"))
                implementation(project(":lib-18"))
                implementation(project(":lib-19"))
                implementation(project(":lib-20"))
            }
        }

        val ohosX64Main by getting {
            dependencies {
                api(libs.compose.multiplatform.export)
                implementation("org.jetbrains.skiko:skiko-ohosx64")
                implementation(project(":lib-01"))
                implementation(project(":lib-02"))
                implementation(project(":lib-03"))
                implementation(project(":lib-04"))
                implementation(project(":lib-05"))
                implementation(project(":lib-06"))
                implementation(project(":lib-07"))
                implementation(project(":lib-08"))
                implementation(project(":lib-09"))
                implementation(project(":lib-10"))
                implementation(project(":lib-11"))
                implementation(project(":lib-12"))
                implementation(project(":lib-13"))
                implementation(project(":lib-14"))
                implementation(project(":lib-15"))
                implementation(project(":lib-16"))
                implementation(project(":lib-17"))
                implementation(project(":lib-18"))
                implementation(project(":lib-19"))
                implementation(project(":lib-20"))
            }
        }
    }
}

android {
    namespace = "com.example.kmptpc_compose_sample"                      // 设置包名
    compileSdk = libs.versions.android.compileSdk.get().toInt()  

    defaultConfig {
        applicationId = "com.example.kmptpc_compose_sample"                   // 应用ID
        minSdk = libs.versions.android.minSdk.get().toInt()     
        targetSdk = libs.versions.android.targetSdk.get().toInt()
        versionCode = 1                                        
        versionName = "1.0"                                    
    }
    packaging {
        resources {
            excludes += "/META-INF/{AL2.0,LGPL2.1}"
        }
    }
    buildTypes {
        getByName("release") {
            isMinifyEnabled = false            
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11     
        targetCompatibility = JavaVersion.VERSION_11    
    }
}

dependencies {
    debugImplementation(libs.compose.ui.tooling)    
}

compose{
    ohos{
        skia("0.9.22.2-OH.0.1.2-06") // 启用自渲染
        // ohrender(" 0.9.22.2-ohrende")  //启用统一渲染
    }
}


// 为 ohosArm64 目标配置依赖处理
val versionCatalog = extensions.getByType<VersionCatalogsExtension>().named("libs")
val cmpVersion = versionCatalog.findVersion("composeMultiplatform")
    .orElseThrow { IllegalStateException("Missing version composeMultiplatform in version catalog") }
    .requiredVersion

configurations.all {
    resolutionStrategy {
        force("org.jetbrains.compose.export:export-ohosarm64:${cmpVersion}")
        force("org.jetbrains.compose.ui:ui-ohosarm64:${cmpVersion}")
        force("org.jetbrains.compose.ui:ui-arkui-ohosarm64:${cmpVersion}")
        force("org.jetbrains.compose.foundation:foundation-ohosarm64:${cmpVersion}")
        force("org.jetbrains.compose.export:export-ohosx64:${cmpVersion}")
        force("org.jetbrains.compose.ui:ui-ohosx64:${cmpVersion}")
        force("org.jetbrains.compose.ui:ui-arkui-ohosx64:${cmpVersion}")
        force("org.jetbrains.compose.foundation:foundation-ohosx64:${cmpVersion}")
    }
}


// 生成约 180MB 填充资源，使 HAP 从约 120MB 增至约 300MB
tasks.register("generateHapPadding") {
    group = "harmony"
    val paddingFile = project.layout.buildDirectory.file("padding/padding.dat").get().asFile
    outputs.file(paddingFile)
    doLast {
        paddingFile.parentFile.mkdirs()
        val buf = ByteArray(1024 * 1024)
        paddingFile.outputStream().use { out ->
            for (i in 0 until 180) { out.write(buf) }
        }
    }
}

// 为不同类型(debug、release)OHOS构建注册Copy任务并发布到Harmony App目录
arrayOf("debug", "release").forEach { type ->
    tasks.register<Copy>("publish${type.capitalizeUS()}BinariesToHarmonyApp") {
        group = "harmony" // 归类到harmony任务组
        dependsOn("link${type.capitalizeUS()}SharedOhosArm64", "link${type.capitalizeUS()}SharedOhosX64", "generateHapPadding")
        duplicatesStrategy = DuplicatesStrategy.INCLUDE
        into(rootProject.file("harmonyApp"))
        from("build/bin/ohosArm64/${type}Shared/libkn_api.h") {
            into("entry/src/main/cpp/include/")
        }
        from(project.file("build/bin/ohosArm64/${type}Shared/libkn.so")) {
            into("entry/libs/arm64-v8a/")
        }
        from("build/bin/ohosX64/${type}Shared/libkn_api.h") {
            into("entry/src/main/cpp/include/")
        }
        from(project.file("build/bin/ohosX64/${type}Shared/libkn.so")) {
            into("entry/libs/x86_64/")
        }
        val composeResourcePackage = "${rootProject.name}.${project.name.lowercase()}.generated.resources"
        from("src/commonMain/composeResources") {
            into("entry/src/main/resources/rawfile/composeResources/$composeResourcePackage/")
        }
        from(layout.buildDirectory.dir("padding")) {
            into("entry/src/main/resources/rawfile/padding/")
        }
    }
}
