import java.io.File

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")
            }
        }
    }


    ohosX64 {
        binaries.sharedLib {
            baseName = "kn"
            export(libs.compose.multiplatform.export)
            linkerOpts("-lz")
            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"))
        }
    }

    ohosArm64 {
        binaries.sharedLib {
            baseName = "kn" // 共享库名称为kn
            export(libs.compose.multiplatform.export) // 导出compose多平台库的接口
            optimized = false
        }
        val main by compilations.getting   // 获取主编译内容
        main.compilerOptions.configure {
            freeCompilerArgs.add("-Xbinary=sanitizer=address")
            freeCompilerArgs.add("-Xbinary=splitBCfile=1")
        }
        val resource by main.cinterops.creating {
            //配置C interop（cinterop）资源
            defFile(file("src/ohosArm64Main/cinterop/resource.def"))        // cinterop定义文件
            includeDirs(file("src/ohosArm64Main/cinterop/include"))        // cinterop包含目录
        }

    }

    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 iosMain by creating {
            dependencies {
                // 依赖配置
            }
        }



        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}")
    }
}

/** 仅清理 harmonyApp 下 entry 的中间目录，与 publish 无关时可单独执行：`:composeApp:cleanHarmonyAppEntryBuildsAndNativeLibs` */
tasks.register("cleanHarmonyAppEntryBuildsAndNativeLibs") {
    group = "harmony"
    notCompatibleWithConfigurationCache("脚本里按存在性删除，动作无法纳入配置缓存序列化")
    val basePath = rootProject.rootDir.absolutePath
    doLast {
        val base = File(basePath)
        val entryBuild = File(base, "harmonyApp/entry/build")
        if (entryBuild.exists()) entryBuild.deleteRecursively()
        val libsArm64 = File(base, "harmonyApp/entry/libs/arm64-v8a")
        if (libsArm64.exists()) libsArm64.deleteRecursively()
        val libsX86 = File(base, "harmonyApp/entry/libs/x86_64")
        if (libsX86.exists()) libsX86.deleteRecursively()
        val cppInclude = File(base, "harmonyApp/entry/src/main/cpp/include")
        if (cppInclude.exists()) cppInclude.deleteRecursively()
    }
}
// 为不同类型(debug、release)OHOS构建注册Copy任务并发布到Harmony App目录
arrayOf("debug", "release").forEach { type ->
    tasks.register<Copy>("publish${type.capitalizeUS()}BinariesToHarmonyApp") {
        dependsOn("cleanHarmonyAppEntryBuildsAndNativeLibs")
        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/")
        }
    }
}


