import java.nio.charset.StandardCharsets

apply plugin: "com.android.application"
apply plugin: "kotlin-android"

def verName = APP_VERSION_NAME
def verCode = 11019

def gitHashProc = new ProcessBuilder("git", "log", "--pretty=format:'%h'", "-n", "1").redirectErrorStream(true).start()
def gitHashBuf = new byte[16]
gitHashProc.getInputStream().read(gitHashBuf)
def gitHash = new String(gitHashBuf, StandardCharsets.UTF_8).trim().replace('\'','')

verName += "-" + gitHash
println(gitHash)

def archs = List.of("arm64-v8a", "armeabi-v7a", "x86", "x86_64")

def officialVer = APP_VERSION_NAME
def officialCode = APP_VERSION_CODE

def serviceAccountCredentialsFile = rootProject.file("service_account_credentials.json")

def beta = verName.contains("preview")

if (serviceAccountCredentialsFile.isFile()) {
    setupPlay(beta)
    play.serviceAccountCredentials = serviceAccountCredentialsFile
} else if (System.getenv().containsKey("ANDROID_PUBLISHER_CREDENTIALS")) {
    setupPlay(beta)
}

void setupPlay(boolean beta) {
    apply plugin: "com.github.triplet.play"
    play {
        track = beta ? "beta" : "production"
        defaultToAppBundles = true
    }
}

repositories {
    mavenCentral()
    google()
    maven {
        url 'https://www.jitpack.io'
        content {
            includeModule 'com.github.UnifiedPush', 'android-connector'
        }
    }
}

configurations {
    compile.exclude module: "support-v4"
}

def keystorePwd = null
def alias = null
def pwd = null
def disableCMakeRelWithDebInfo = System.getenv("COMPILE_NATIVE") == null

Properties properties
def base64 = System.getenv("LOCAL_PROPERTIES")
if (base64 != null && !base64.isBlank()) {
    properties = new Properties()
    properties.load(new ByteArrayInputStream(Base64.decoder.decode(base64)))
} else if (project.rootProject.file("local.properties").exists()) {
    properties = new Properties()
    properties.load(project.rootProject.file("local.properties").newDataInputStream())
}

if (properties != null) {
    keystorePwd = properties.getProperty("KEYSTORE_PASS")
    alias = properties.getProperty("ALIAS_NAME")
    pwd = properties.getProperty("ALIAS_PASS")
}

keystorePwd = keystorePwd ?: System.getenv("KEYSTORE_PASS")
alias = alias ?: System.getenv("ALIAS_NAME")
pwd = pwd ?: System.getenv("ALIAS_PASS")

def targetTask = ""
if (!gradle.startParameter.taskNames.isEmpty()) {
    if (gradle.startParameter.taskNames.size == 1) {
        targetTask = gradle.startParameter.taskNames[0].toLowerCase()
    }
}

def nativeTarget = System.getenv("NATIVE_TARGET")
if (nativeTarget == null) nativeTarget = ""

android {
    compileSdk 35
    buildToolsVersion "35.0.0"
    ndkVersion rootProject.ext.ndkVersion

    buildFeatures.aidl = true
    buildFeatures.buildConfig = true

    defaultConfig.applicationId = APP_PACKAGE


    splits {

        abi {
            if (nativeTarget.isBlank()) {
                enable true
                reset()
                include 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
                universalApk false
            } else if (nativeTarget.toLowerCase().equals("universal")) {
                enable false
                universalApk true
            } else if (!archs.contains(nativeTarget.toLowerCase())) {
                enable false
                universalApk false
            }
        }

    }

    defaultConfig {
        minSdkVersion 19
        //noinspection ExpiredTargetSdkVersion,OldTargetApi
        targetSdkVersion 34

        versionName verName
        versionCode verCode

        def appId = "1391584"
        def appHash = "355c91550b0d658cfb7ff89dcf91a08c"

        //obtain your own keys at https://core.telegram.org/api/obtaining_api_id

        if (properties != null) {
            appId = properties.getProperty("TELEGRAM_APP_ID") ?: System.getenv("TELEGRAM_APP_ID") ?: appId
            appHash = properties.getProperty("TELEGRAM_APP_HASH") ?: System.getenv("TELEGRAM_APP_HASH") ?: appHash
        } else if (System.getenv("TELEGRAM_APP_ID") != null) {
            appId = System.getenv("TELEGRAM_APP_ID") ?: appId
            appHash = System.getenv("TELEGRAM_APP_HASH") ?: appHash
        }
        System.out.printf("api_id=%s", appId)


        buildConfigField "String", "OFFICIAL_VERSION", "\"" + officialVer + "\""
        buildConfigField "int", "OFFICIAL_VERSION_CODE", officialCode + ""
        buildConfigField "int", "APP_ID", appId
        buildConfigField "String", "APP_HASH", "\"" + appHash + "\""
        buildConfigField "int", "VERSION_NUM", "6"
        resValue "string", "package_name", APP_PACKAGE

//        ndk {
//            abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
//        }

        externalNativeBuild {
            cmake {
                version "3.10.2"
                arguments '-DANDROID_STL=c++_static', '-DANDROID_PLATFORM=android-21' //, '-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON'
            }
        }

    }

    bundle {
        language {
            enableSplit = false
        }
    }

    externalNativeBuild {
        cmake {
            path "jni/CMakeLists.txt"
        }
    }


    dexOptions {
        jumboMode = true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17

        coreLibraryDesugaringEnabled true
    }

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

    testOptions {
        unitTests.includeAndroidResources = true
    }

    signingConfigs {
        release {
            storeFile project.file("release.keystore")
            storePassword keystorePwd
            keyAlias alias
            keyPassword pwd
        }
    }

    buildTypes {
        debug {
            isDefault true
            debuggable true
            jniDebuggable true
            multiDexEnabled true
            signingConfig keystorePwd == null ? signingConfigs.debug : signingConfigs.release
            ndk.debugSymbolLevel = 'FULL'
        }

        release {
            debuggable false
            jniDebuggable false
            minifyEnabled true
            shrinkResources true
            multiDexEnabled true
            proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro", '../TMessagesProj/proguard-rules-beta.pro'
            matchingFallbacks = ["release", "debug"]
            signingConfig keystorePwd == null ? signingConfigs.debug : signingConfigs.release
        }

        foss {
            debuggable false
            jniDebuggable false
            minifyEnabled true
            shrinkResources true
            multiDexEnabled true
            proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro", '../TMessagesProj/proguard-rules-beta.pro'
            matchingFallbacks = ["release", "debug"]
        }

        fdroidRelease {
            initWith foss
            matchingFallbacks = ["release", "debug"]
        }
    }

    sourceSets {

        main {
            jni.srcDirs = []
            aidl.srcDirs = ["src/main/aidl"]
            assets.srcDirs = ["src/main/assets"]
        }

        debug {
            java {
                srcDirs "src/main/java"
            }
            jni.srcDirs = ["./jni/"]
        }

        release {
            jni.srcDirs = []
            jniLibs {
                srcDir "src/main/libs"
            }
        }

        foss {
            jni {
                srcDirs = ["./jni/"]
            }
        }

        fdroidRelease {
            jni {
                srcDirs = ["./jni/"]
            }
            jniLibs.srcDirs = []
        }

    }

    flavorDimensions ["version"]

    sourceSets.all { set ->
        if (set.name.startsWith("full")) {
            set.dependencies {
                implementation fileTree("libs")
            }
        }
    }

    tasks.all { task ->
        if (((task.name.endsWith("Ndk") || task.name.startsWith("generateJsonModel") || task.name.startsWith("externalNativeBuild"))) && !(task.name.contains("Debug") || task.name.contains("Foss") || task.name.contains("Fdroid"))) {
            task.enabled = false
        }
        if (task.name.contains("uploadCrashlyticsMappingFile")) {
            enabled = false
        }
        if (disableCMakeRelWithDebInfo && task.name.contains("CMakeRelWithDebInfo") && !targetTask.contains("fdroid")) {
            enabled = false
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            outputFileName = outputFileName.replace("-mini", "").replace("-release", "").replace("TMessagesProj", "Momo-v" + versionName)
        }
    }

}

def fcmVersion = "23.0.7"
def crashlyticsVersion = "18.2.12"
def playCoreVersion = "1.10.3"

dependencies {

    implementation "androidx.browser:browser:1.8.0"
    implementation "androidx.core:core-ktx:1.13.1"
    implementation 'androidx.fragment:fragment-ktx:1.7.1'
    implementation "androidx.palette:palette-ktx:1.0.0"
    implementation "androidx.viewpager:viewpager:1.0.0"
    implementation "androidx.exifinterface:exifinterface:1.3.7"
    implementation "androidx.interpolator:interpolator:1.0.0"
    implementation "androidx.dynamicanimation:dynamicanimation:1.0.0"
    implementation "androidx.multidex:multidex:2.0.1"
    implementation "androidx.sharetarget:sharetarget:1.2.0"
    implementation 'androidx.interpolator:interpolator:1.0.0'
    implementation 'androidx.biometric:biometric:1.1.0'

    implementation 'javax.annotation:javax.annotation-api:1.3.2'

    // just follow official
//    implementation 'com.google.android.gms:play-services-cast-framework:21.4.0'
    implementation("androidx.mediarouter:mediarouter:1.7.0") {
        exclude group: 'androidx.recyclerview'
    }
//    implementation 'org.nanohttpd:nanohttpd:2.3.1'

    compileOnly 'org.checkerframework:checker-qual:2.5.2'
    compileOnly 'org.checkerframework:checker-compat-qual:2.5.0'

    // don"t change this :)
    //noinspection GradleDependency
    implementation "com.googlecode.mp4parser:isoparser:1.0.6"

    implementation "com.google.code.gson:gson:2.11.0"
    implementation "org.osmdroid:osmdroid-android:6.1.14"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:2.0.21"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1"

    implementation 'com.github.UnifiedPush:android-connector:2.3.1'
    implementation "com.squareup.okhttp3:okhttp:5.0.0-alpha.10"
    implementation 'com.neovisionaries:nv-websocket-client:2.14'
    implementation 'dnsjava:dnsjava:3.4.1'
    implementation "org.dizitart:nitrite:4.3.0"
    implementation 'org.dizitart:nitrite-mvstore-adapter:4.3.0'
    implementation 'org.apache.commons:commons-lang3:3.17.0'

    // for whisper
    implementation 'org.tensorflow:tensorflow-lite:2.16.1'
    implementation 'org.tensorflow:tensorflow-lite-support:0.4.4'
    // ogg to samples
//    implementation 'com.soywiz.korlibs.korge:korio:4.0.0'
    implementation 'io.github.jaredmdobson:concentus:1.0.2'
    implementation "org.gagravarr:vorbis-java-core:0.8"

    implementation "com.jakewharton:process-phoenix:2.1.2"
    implementation 'com.google.guava:guava:31.1-android'
//    implementation 'com.airbnb.android:lottie:6.4.0' // 030: removed from upstream
//    implementation 'com.google.android.play:integrity:1.3.0'
//    implementation 'com.google.android.gms:play-services-safetynet:18.0.1'

    compileOnly 'org.yaml:snakeyaml:2.3'
//    fullImplementation 'org.yaml:snakeyaml:2.3'

    implementation project(":openpgp-api")

    compileOnly fileTree("libs")

//    compileOnly "com.google.firebase:firebase-messaging:$fcmVersion"
//    compileOnly "com.google.firebase:firebase-crashlytics:$crashlyticsVersion"
//    compileOnly "com.google.android.play:core:$playCoreVersion"

//    debugImplementation 'com.google.android.gms:play-services-maps:18.1.0'
//    debugImplementation 'com.google.android.gms:play-services-location:20.0.0'
//    releaseImplementation 'com.google.android.gms:play-services-maps:18.1.0'
//    releaseImplementation 'com.google.android.gms:play-services-location:20.0.0'

//    debugImplementation "com.google.firebase:firebase-messaging:$fcmVersion"
//    debugImplementation "com.google.firebase:firebase-crashlytics:$crashlyticsVersion"
//    debugImplementation "com.google.android.play:core:$playCoreVersion"
//    releaseImplementation "com.google.firebase:firebase-messaging:$fcmVersion"
//    releaseImplementation "com.google.firebase:firebase-crashlytics:$crashlyticsVersion"
//    releaseImplementation "com.google.android.play:core:$playCoreVersion"

    debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.14'

    testImplementation "junit:junit:4.13.2"
    testImplementation "androidx.test:core:1.6.1"
    testImplementation "org.robolectric:robolectric:4.5.1"

//    implementation 'com.google.mlkit:translate:17.0.3'

    constraints {
        implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.8.0") {
            because("kotlin-stdlib-jdk7 is now a part of kotlin-stdlib")
        }
        implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0") {
            because("kotlin-stdlib-jdk8 is now a part of kotlin-stdlib")
        }
    }
//    implementation 'com.google.android.recaptcha:recaptcha:18.4.0'

    coreLibraryDesugaring "com.android.tools:desugar_jdk_libs:2.1.5"

}

//apply plugin: "com.google.gms.google-services"
//apply plugin: "com.google.firebase.crashlytics"

android {


    packagingOptions {
        jniLibs {
            excludes += ['/fabric/**', '/META-INF/native-image/**']
            pickFirsts += ['**/libtmessages.*.so']
        }
        resources {
            excludes += ['/fabric/**', '/META-INF/*.version', '/META-INF/*.kotlin_module', '/META-INF/native-image/**', '/builddef.lst', '/*.txt', '/DebugProbesKt.bin', '/okhttp3/internal/publicsuffix/NOTICE', '/META-INF/INDEX.LIST']
        }
    }
    namespace "org.telegram.messenger"
    lint {
        disable 'MissingTranslation', 'ExtraTranslation', 'BlockedPrivateApi'
    }

    tasks.all { task ->
        if (task.name.startsWith("uploadCrashlyticsMappingFile")) {
            task.enabled = false
        } else if (task.name.contains("Crashlytics")) {
            task.enabled = false
        } else if (task.name.endsWith("GoogleServices")) {
            task.enabled = false
        }
    }

    namespace 'org.telegram.messenger'
}
