import org.jetbrains.kotlin.gradle.dsl.JvmTarget

plugins {
    alias(libs.plugins.kotlinMultiplatform)
    alias(libs.plugins.androidLibrary)
}

kotlin {
    androidTarget {
        compilerOptions {
            jvmTarget.set(JvmTarget.JVM_11)
        }
    }
    
    listOf(
        iosArm64(),
        iosSimulatorArm64()
    ).forEach { iosTarget ->
        iosTarget.binaries.framework {
            baseName = "Shared"
            isStatic = true
        }
    }

    ohosArm64 {
        binaries {
            sharedLib {
                baseName = "kn"
                // 链接静态库目录和库名，使用 --whole-archive 强制包含静态库所有符号
                freeCompilerArgs += listOf("-Xbinary=sanitizer=address")
            }
            staticLib {
                baseName = "kn"
            }
        }

    }

    ohosX64 {
        binaries {
            sharedLib {
                baseName = "kn"
                freeCompilerArgs += listOf("-Xbinary=sanitizer=address")
            }
            staticLib {
                baseName = "kn"
            }
        }

    }

    sourceSets {
        commonMain.dependencies {
            // put your Multiplatform dependencies here
        }
        commonTest.dependencies {
            implementation(libs.kotlin.test)
        }
        val commonMain by getting

        val ohosArm64Main by getting{
            dependsOn(commonMain)
            dependencies {
            }
        }
        val ohosX64Main by getting{
            dependsOn(commonMain)
            dependencies {
            }
        }
    }
}





android {
    namespace = "com.dong.nocomposedemo.shared"
    compileSdk = libs.versions.android.compileSdk.get().toInt()
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }
    defaultConfig {
        minSdk = libs.versions.android.minSdk.get().toInt()
    }
}

// commonizer 只认识官方 Konan 目标，不认识 ohos_x64/ohos_arm64，任务可能延迟注册，故在 afterEvaluate 中禁用
// IDE 的 ohosMain 依赖解析会读取 commonizedNativeDistributionLocation.txt，必须在配置阶段就创建，否则 prepareKotlinIdeaImport 报 FileNotFoundException
val commonizedDir = file("build/kotlin")
commonizedDir.mkdirs()
File(commonizedDir, "commonizedNativeDistributionLocation.txt").writeText(commonizedDir.absolutePath)

afterEvaluate {
    listOf("commonizeNativeDistribution", "commonizeCInterop").forEach { taskName ->
        tasks.findByName(taskName)?.let { it.enabled = false }
    }
}

android {
    namespace = "com.eazytec.kmpdemo.shared"
    compileSdk = libs.versions.android.compileSdk.get().toInt()
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }
    defaultConfig {
        minSdk = libs.versions.android.minSdk.get().toInt()
    }
}

// 使用 Konan 自带的 OHOS LLVM 工具链（用于交叉编译静态库），根据主机平台自动选择
val konanDepsDir: File = file(System.getProperty("user.home") + "/.konan/dependencies")
val isWindows = System.getProperty("os.name").lowercase().contains("win")
val execExt = if (isWindows) ".exe" else ""

val konanOhosLlvmBin: File? by lazy {
    val osArch = System.getProperty("os.arch")
    val osName = System.getProperty("os.name").lowercase()
    val toolchain = when {
        osName.contains("mac") && osArch == "aarch64" -> "llvm-19.1.7-aarch64-macos-ohos-2"
        osName.contains("mac")                        -> "llvm-19.1.7-x64-macos-ohos-2"
        osName.contains("linux")                      -> "llvm-19.1.7-x64-linux-ohos-2"
        osName.contains("win")                        -> "llvm-19.1.7-x64-mingw-ohos-2"
        else -> null
    }
    toolchain?.let { konanDepsDir.resolve("$it/bin").takeIf { dir -> dir.isDirectory } }
}

val ohosSysrootArm64: File? by lazy {
    listOf("sysroot-ohos-aarch64-6.0.2.640-02", "sysroot-ohos-aarch64-6.0.0.858-02")
        .map { konanDepsDir.resolve(it) }.firstOrNull { it.isDirectory }
}

val ohosSysrootX64: File? by lazy {
    listOf("sysroot-ohos-x86_64-6.0.0.858-02")
        .map { konanDepsDir.resolve(it) }.firstOrNull { it.isDirectory }
}

// Harmony App 输出目录（支持命令行 --harmonyAppPath）
val harmonyAppDir: File = run {
    val cliPath = project.findProperty("harmonyAppPath") as String?
    if (cliPath.isNullOrBlank()) {
        // 默认：项目根目录 /harmonyApp
        rootProject.file("harmonyApp")
    } else {
        // 命令行传入的路径
        file(cliPath)
    }
}
// 字符串首字母大写工具函数
fun String.capitalizeUS(): String = this.replaceFirstChar {
    if (it.isLowerCase()) it.titlecase() else it.toString()
}
// 为不同类型(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") // 依赖于OHOS shared lib的链接任务
        into(harmonyAppDir) // 输出目标目录
        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/")           // 指定目标目录
        }
    }
}


// 发布 ohosX64 产物到 harmonyapp，供模拟器（x86_64）使用
arrayOf("debug", "release").forEach { type ->
    val capitalizedType = type.replaceFirstChar { it.uppercase() }
    tasks.register<Copy>("publish${capitalizedType}BinariesToHarmonyAppX64") {
       group = "harmony" // 归类到harmony任务组
        dependsOn("link${type.capitalizeUS()}SharedOhosX64") // 依赖于OHOS shared lib的链接任务
        into(harmonyAppDir) // 输出目标目录
        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/")           // 指定目标目录
        }
    }
}





