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

android {
    namespace = "com.fabledsword.minstrel"
    compileSdk = flutter.compileSdkVersion
    ndkVersion = flutter.ndkVersion

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

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

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId = "com.fabledsword.minstrel"
        // You can update the following values to match your application needs.
        // For more information, see: https://flutter.dev/to/review-gradle-config.
        minSdk = flutter.minSdkVersion
        targetSdk = flutter.targetSdkVersion
        versionCode = flutter.versionCode
        versionName = flutter.versionName
    }

    // Real release signing config — populated only when CI exports
    // ANDROID_KEYSTORE_PATH (decoded from a base64 secret) plus the
    // matching password/alias env vars. Without these (local
    // `flutter build apk --release` runs), the release build falls
    // through to the debug keystore so local builds still work.
    //
    // Why this matters: Flutter's default `flutter run --release` and
    // CI's earlier setup both signed with the per-machine debug
    // keystore (~/.android/debug.keystore). Every CI runner generated
    // its own debug key, so consecutive release APKs had different
    // signatures and Android refused to upgrade an existing install.
    val keystorePath: String? = System.getenv("ANDROID_KEYSTORE_PATH")
    if (keystorePath != null && keystorePath.isNotEmpty()) {
        signingConfigs {
            create("release") {
                storeFile = file(keystorePath)
                storePassword = System.getenv("ANDROID_STORE_PASSWORD")
                keyAlias = System.getenv("ANDROID_KEY_ALIAS")
                keyPassword = System.getenv("ANDROID_KEY_PASSWORD")
            }
        }
    }

    buildTypes {
        release {
            signingConfig = if (keystorePath != null && keystorePath.isNotEmpty()) {
                signingConfigs.getByName("release")
            } else {
                // Local-only fallback so `flutter run --release` works
                // without the keystore. CI must export ANDROID_KEYSTORE_PATH.
                signingConfigs.getByName("debug")
            }
        }
    }
}

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