plugins {
    id("com.android.application")
    id("kotlin-android")
    // Flutter Gradle 插件必须放在 Android 与 Kotlin Gradle 插件之后应用。
    id("dev.flutter.flutter-gradle-plugin")
}

import java.io.File
import java.io.FileInputStream
import java.util.Properties

val keystoreProperties = Properties()
val keystorePropertiesFile = rootProject.file("key.properties")
if (keystorePropertiesFile.exists()) {
    FileInputStream(keystorePropertiesFile).use { keystoreProperties.load(it) }
}

val defaultReleaseStoreFile = rootProject.file("../../../tool/key.jks")
fun resolveKeystoreFile(rawPath: String?): File {
    val candidate = rawPath?.trim().orEmpty()
    if (candidate.isEmpty()) {
        return defaultReleaseStoreFile
    }

    val expandedHome = if (candidate.startsWith("~/") || candidate == "~") {
        candidate.replaceFirst("~", System.getProperty("user.home"))
    } else {
        candidate
    }

    val normalized = expandedHome.replace('\\', File.separatorChar).replace('/', File.separatorChar)
    val storeFile = File(normalized)
    return if (storeFile.isAbsolute) storeFile else rootProject.file(normalized)
}

val releaseStoreFile = resolveKeystoreFile(keystoreProperties["storeFile"] as String?)
val releaseKeyAlias = keystoreProperties["keyAlias"] as String? ?: "my-key-alias"
val releaseKeyPassword = keystoreProperties["keyPassword"] as String? ?: "123456"
val releaseStorePassword = keystoreProperties["storePassword"] as String? ?: "123456"

android {
    namespace = "com.yuanxuan.webshell.web_android_shell"
    compileSdk = flutter.compileSdkVersion
    ndkVersion = flutter.ndkVersion

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_17.toString()
    }

    defaultConfig {
        // 待补充：请替换成你自己的唯一应用标识。
        applicationId = "com.yuanxuan.webshell.web_android_shell"
        // 下面这些值可以按应用实际需求调整。
        // 更多说明可参考：https://flutter.dev/to/review-gradle-config。
        minSdk = flutter.minSdkVersion
        // 为兼容旧版系统 WebView，这里保持稳定的 targetSdk。
        targetSdk = 34
        versionCode = flutter.versionCode
        versionName = flutter.versionName
    }

    signingConfigs {
        create("release") {
            keyAlias = releaseKeyAlias
            keyPassword = releaseKeyPassword
            storeFile = releaseStoreFile
            storePassword = releaseStorePassword
        }
    }

    buildTypes {
        release {
            signingConfig = signingConfigs.getByName("release")
        }
    }
}

flutter {
    source = "../.."
}
