import java.util.Properties
import java.io.FileInputStream
import java.io.FileOutputStream

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

// ============================================
// Auto-increment version code on each build
// ============================================
val versionPropertiesFile = rootProject.file("app/version.properties")
val versionProperties = Properties()

fun calculateNextVersionCode(): Int {
    if (versionPropertiesFile.exists()) {
        versionProperties.load(FileInputStream(versionPropertiesFile))
    }
    val currentCode = versionProperties.getProperty("VERSION_CODE", "0").toInt()
    val newCode = currentCode + 1
    versionProperties.setProperty("VERSION_CODE", newCode.toString())
    versionProperties.store(FileOutputStream(versionPropertiesFile), "Auto-generated version code - DO NOT EDIT MANUALLY")
    return newCode
}

// Get auto-incremented version code
val autoVersionCode = calculateNextVersionCode()

// Version name format: major.minor.patch (from pubspec.yaml) + build number
// Example: 1.0.0.123
fun getAutoVersionName(): String {
    val flutterVersionName = flutter.versionName
    return "$flutterVersionName.$autoVersionCode"
}

android {
    namespace = "com.rwadurian.mining_app"
    compileSdk = flutter.compileSdkVersion
    ndkVersion = flutter.ndkVersion

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

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

    defaultConfig {
        applicationId = "com.rwadurian.mining_app"
        minSdk = 24
        targetSdk = flutter.targetSdkVersion
        // Auto-incremented version code and name
        versionCode = autoVersionCode
        versionName = getAutoVersionName()

        // 多dex支持
        multiDexEnabled = true
    }

    buildTypes {
        debug {
            // Debug配置
            isDebuggable = true
            // 不设置 applicationIdSuffix，确保 debug/release 包名一致
            // 避免升级时出现两个相同图标的应用
            versionNameSuffix = "-debug"
        }
        release {
            // Release配置
            isMinifyEnabled = true
            isShrinkResources = true
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
            // 暂时使用debug签名，后续配置正式签名
            signingConfig = signingConfigs.getByName("debug")
        }
    }
}

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