import java.util.Properties

plugins {
    id("com.android.application")
    id("kotlin-android")
    // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
    id("dev.flutter.flutter-gradle-plugin")
}

val localProperties = Properties().apply {
    val localPropertiesFile = rootProject.file("local.properties")
    if (localPropertiesFile.exists()) {
        localPropertiesFile.inputStream().use { load(it) }
    }
}
val developmentVersionCode = System.getenv("SMPLAYER_ANDROID_VERSION_CODE")?.let { rawVersionCode ->
    rawVersionCode.toIntOrNull()?.takeIf { versionCode -> versionCode > 0 }
        ?: error("SMPLAYER_ANDROID_VERSION_CODE must be a positive integer")
}
val flutterVersionCode = developmentVersionCode
    ?: localProperties.getProperty("flutter.versionCode")?.toIntOrNull()
    ?: 1
val flutterVersionName = localProperties.getProperty("flutter.versionName") ?: "1.0.0"

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

android {
    namespace = "com.smplayer.smplayer"
    compileSdk = flutter.compileSdkVersion
    ndkVersion = flutter.ndkVersion

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

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

    defaultConfig {
        applicationId = "com.smplayer.smplayer"
        // fvp(libmdk) 与 media_kit(libmpv) 在 Android 上的硬解基线。
        minSdk = maxOf(flutter.minSdkVersion, 24)
        targetSdk = flutter.targetSdkVersion
        versionCode = flutterVersionCode
        versionName = flutterVersionName
        // ABI 限制策略：见下方 buildTypes。defaultConfig 不收缩，保留多 ABI 让
        // debug 在 x86_64 emulator 上仍能加载 fvp libmdk.so / media_kit libmpv.so；
        // release 包仅 arm64-v8a 以匹配 media3 FFmpeg AAR 并控制包体。
    }

    signingConfigs {
        if (keystorePropertiesFile.exists()) {
            create("release") {
                storeFile = file(keystoreProperties["storeFile"] as String)
                storePassword = keystoreProperties["storePassword"] as String
                keyAlias = keystoreProperties["keyAlias"] as String
                keyPassword = keystoreProperties["keyPassword"] as String
            }
        }
    }

    // 本地 debug 在没有 key.properties 时使用 Android debug 签名；release 构建
    // 绝不回退到临时 debug 证书，避免发布无法覆盖安装的 APK。
    val releaseSigningConfig = if (keystorePropertiesFile.exists()) {
        signingConfigs.getByName("release")
    } else {
        null
    }

    buildTypes {
        debug {
            applicationIdSuffix = ".dev"
            manifestPlaceholders["appLabel"] = "smplayer-dev"
            signingConfig = releaseSigningConfig ?: signingConfigs.getByName("debug")
        }
        release {
            manifestPlaceholders["appLabel"] = "smplayer"
            if (releaseSigningConfig != null) {
                signingConfig = releaseSigningConfig
            }
            ndk {
                // 仅 release 收缩到 arm64-v8a：与 media3_engine plugin 自编译的
                // FFmpeg decoder AAR 对齐（其只含 arm64-v8a），包体最小化。
                // debug 不限制 → x86_64 / arm64 emulator 上 fvp / media_kit 仍可运行。
                abiFilters += listOf("arm64-v8a")
            }
        }
    }
}

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

// media3_engine plugin 把 media3-decoder-ffmpeg-*.aar 标为 compileOnly（AGP 8
// 禁止 library module 直接 implementation 本地 .aar）。在 app 这一层把所有本地
// .aar 实际打入 APK；目前只有 media3 FFmpeg decoder AAR，使用 include 通配避免
// 后续新增 AAR 时再改这里。
dependencies {
    implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.aar"))))
}
