// Makes the versionCode this action resolved authoritative for native Gradle
// builds. Applied with --init-script by the "Build release Android App Bundle
// with Gradle" step; never applied to a Flutter build, which takes the number
// through `flutter build --build-number` and already works.
//
// Why an init script rather than AGP's injected properties
// -------------------------------------------------------
// The obvious answer looks like
//     ./gradlew ... -Pandroid.injected.version.code=<N>
// and it is a silent no-op on every app in this fleet. Those properties were
// removed in AGP 7.3 — verified by disassembling IntegerOption/StringOption
// across cached AGP releases: android.injected.version.code and
// android.injected.version.name are present in 4.1 and 7.1 and gone from 7.3
// onward. Passing them to an AGP 8.x build changes nothing and reports nothing,
// so the stale versionCode still ships and Play still answers
// "Version code N has already been used".
//
// The supported override is the Variant API, which is what this does. It needs
// no cooperation from the app and edits none of its sources, so it works
// whatever the build file does — including the indirection that defeats
// resolve_android.py's literal rewrite:
//     ext.code = 31
//     versionCode code
//
// An unset variable means "no opinion": the project's own value stands. That is
// what keeps versionName alone unless a build-name was actually resolved.

def readSetting = { String name ->
    def value = System.getenv(name)
    return value?.trim() ? value.trim() : null
}

def versionName = readSetting('ANDROID_BUILD_NAME')
def versionCodeText = readSetting('ANDROID_BUILD_NUMBER')

Integer versionCode = null
if (versionCodeText != null) {
    try {
        versionCode = Integer.parseInt(versionCodeText)
    } catch (NumberFormatException ignored) {
        println "::warning::ANDROID_BUILD_NUMBER is not an integer (${versionCodeText}); " +
                "leaving the project's own versionCode in place"
    }
}

if (versionCode != null || versionName != null) {
    gradle.beforeProject { project ->
        project.plugins.withId('com.android.application') {
            // AGP 7.0+ — the current Variant API.
            def components = project.extensions.findByName('androidComponents')
            if (components != null) {
                components.onVariants(components.selector().all()) { variant ->
                    variant.outputs.each { output ->
                        if (versionCode != null) output.versionCode.set(versionCode)
                        if (versionName != null) output.versionName.set(versionName)
                    }
                    println "${project.path} ${variant.name}: versionCode=" +
                            "${versionCode ?: 'unchanged'} versionName=${versionName ?: 'unchanged'}"
                }
                return
            }
            // AGP < 7.0 — no androidComponents extension exists yet.
            def android = project.extensions.findByName('android')
            if (android == null) {
                println "::warning::${project.path} applies com.android.application but exposes " +
                        "neither androidComponents nor android; versionCode not overridden"
                return
            }
            android.applicationVariants.all { variant ->
                variant.outputs.each { output ->
                    if (versionCode != null) output.versionCodeOverride = versionCode
                    if (versionName != null) output.versionNameOverride = versionName
                }
                println "${project.path} ${variant.name}: versionCode=" +
                        "${versionCode ?: 'unchanged'} versionName=${versionName ?: 'unchanged'}"
            }
        }
    }
}
