
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")
            // 避免 release 优化在模拟器上触发 SIGILL（非法指令）
            optimized = false
        }
         // 禁用内联类可能有助于 NAPI
        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")
            // 避免 release 优化在模拟器上触发 SIGILL（非法指令）
            optimized = false
        }
        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) //需要单独依赖
        }
        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)
            // Navigation 库测试 Demo：使用 Maven 依赖（版本见 libs.versions.toml 的 androidx-navigation）
            implementation(libs.compose.navigation)
        }

        val ohosArm64Main by getting {
            dependencies {
                api(libs.compose.multiplatform.export)
                //导出skiko api 用于demo中测试
                implementation("org.jetbrains.skiko:skiko-ohosarm64")
            }
        }

        val ohosX64Main by getting {
            dependencies {
                api(libs.compose.multiplatform.export)
                implementation("org.jetbrains.skiko:skiko-ohosx64")
            }
        }
    }
}

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

    defaultConfig {
        applicationId = "com.example.toolchain"                   // 应用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 {
        // TODO: 强制刷新 compose ui ohosarm64 依赖
        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}")
        // ohosX64
        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}")
    }
}


// 为不同类型(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")
        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/")
        }
    }
}
