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)
    id("org.jetbrains.kotlin.native.cocoapods")
}

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

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

    cocoapods {
        summary = "TestToolChainDemo Compose Multiplatform shared module"
        homepage = "https://github.com/eazytec/mytoolchain"
        version = "1.0"
        ios.deploymentTarget = "15.3"
        podfile = project.file("../iosApp/Podfile")
        framework {
            baseName = "ComposeApp"
            isStatic = true
        }
    }


    // 配置OHOS（华为鸿蒙）多架构目标
    listOf(
        ohosArm64(),   // 真机 arm64
        ohosX64()      // 模拟器/开发机 x64
    ).forEach { ohosTarget ->
        ohosTarget.binaries.sharedLib {
            baseName = "kn" // 共享库名称为kn
            export(libs.compose.multiplatform.export) // 导出compose多平台库的接口
            // 确保链接系统 zlib，使 libkn.so 的 NEEDED 包含 libz.so
            linkerOpts("-lz")
            // 避免 release 优化在模拟器上触发 SIGILL（非法指令）
            optimized = false
            // 渲染模式
            // 背景：当 libkn.so 为旧编译产物时，其 DT_NEEDED 可能缺少以下库（正确构建时
            // NativeTasksConfiguration.kt 已通过 -l 选项将它们写入 DT_NEEDED）。
            // 在 build.gradle.kts 中统一补全，避免在 CMakeLists.txt 中硬编码。
            val rendererBackend = rootProject.findProperty("rendererBackend")?.toString() ?: "fusion-renderer"
            if (rendererBackend == "fusion-renderer") {
                linkerOpts(
                    "-lnative_drawing",    // OH_Drawing_*（字体、绘制）
                    "-limage_source",       // OH_ImageSourceNative_*（图像解码）
                    "-lpixelmap",           // OH_PixelMap_*
                    "-lpixelmap_ndk.z",     // OH_PixelMapNdk_*
                    "-lnative_window",      // OH_NativeWindow_*
                    "-lace_napi.z",         // N-API
                    "-lhilog_ndk.z",        // HiLog 日志
                    "-lhitrace_ndk.z",      // HiTrace 性能追踪
                    "-luv",                 // libuv 事件循环
                    "-lunwind",             // 栈展开
                    "-licu",               // ICU 文本处理
                )
            }
        }
        ohosTarget.compilations.getByName("main") {
            compilerOptions.configure {
                freeCompilerArgs.add("-Xbinary=sanitizer=address")
            }
            val resource by cinterops.creating {
                defFile(file("src/ohosArm64Main/cinterop/resource.def"))
               includeDirs(file("src/ohosArm64Main/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 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)
}

//// OHOS 渲染模式二选一：自渲染（Skia）或统一渲染（ohrender）。切换时只保留其一，另一行注释掉。
//compose {
//    ohos {
//        skia("0.9.22.2-0.2.0-05")           // 自渲染：Compose 用 Skia 自绘
//        // ohrender("0.9.22.2-0.1.0")       // 统一渲染：与 ArkUI 统一渲染管线；启用时注释上一行
//    }
//}


// 为 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/arm64-v8a/")         // 指定目录
        }
        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/x86_64/")
        }
        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/")
        }
    }
}


