import io.sentry.android.gradle.extensions.InstrumentationFeature
import io.sentry.android.gradle.instrumentation.logcat.LogcatLevel

import java.nio.file.Paths

apply plugin: "com.android.application"
apply plugin: "kotlin-android"
apply plugin: "org.jetbrains.kotlin.plugin.serialization"
apply plugin: "io.sentry.android.gradle"
apply plugin: "io.objectbox"

apply plugin: 'org.telegram.build-plugin'
apply plugin: 'org.telegram.build-app-plugin'
apply plugin: 'xyz.nagram.auto-patch-plugin'
apply plugin: 'idea'

idea {
    module {
        excludeDirs += [
            file('jni/td'),
            file('jni/third_party/absl'),
            file('jni/third_party/boringssl'),
            file('jni/third_party/dav1d'),
            file('jni/third_party/ffmpeg'),
            file('jni/third_party/libvpx'),
            file('jni/third_party/libyuv'),
            file('jni/third_party/openh264'),
            file('jni/third_party/xiph'),
            file('jni/third_party/wamr'),
            file('jni/third_party/libprisma'),
            file('jni/third_party/boost-regex'),
            file('jni/tgcalls'),
            file('jni/tlottie'),
            file('jni/voip/webrtc'),
            file('jni/sqlite')
        ]
    }
}

def verName = APP_VERSION_NAME
def verCode = 1258


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

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

def keystorePwd = null
def alias = null
def pwd = null
def sentry_token = System.getenv("SENTRY_AUTH_TOKEN")
def nagram_build_args = System.getenv("NAGRAM_BUILD_ARGS")

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")
    sentry_token = properties.getProperty("SENTRY_AUTH_TOKEN", sentry_token)
    nagram_build_args = properties.getProperty("NAGRAM_BUILD_ARGS", nagram_build_args)
}

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

def sentry_upload = sentry_token != null && !sentry_token.isEmpty()

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 = ""

def isWindows = System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1

android {
    compileSdkVersion 36
    buildToolsVersion '36.0.0'
    ndkVersion rootProject.ext.ndkVersion // 27.2.12479018

    defaultConfig.applicationId = "xyz.nextalone.nagram"

    sourceSets {

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

        debug {
            java {
                srcDirs "src/main/java"
            }
        }

        release {
            java {
                srcDirs "src/main/java"
            }
        }
    }

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

    lintOptions {
        disable 'MissingTranslation'
        disable 'ExtraTranslation'
        disable 'BlockedPrivateApi'
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11

        coreLibraryDesugaringEnabled true
    }

    splits {

        abi {
            if (targetTask.contains("fdroid")) {
                enable false
                universalApk true
            } else {
                enable true
                reset()
                universalApk false
                if (!nativeTarget.isBlank()) {
                    include nativeTarget
                } else {
                    include 'armeabi-v7a', 'arm64-v8a'
                }
            }
        }

    }

    defaultConfig {
        minSdkVersion 23
        //noinspection ExpiredTargetSdkVersion,OldTargetApi
        targetSdkVersion 36

        versionName verName
        versionCode verCode

        def appId = "0"
        def appHash = ""

        //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
        }

        buildConfigField "String", "BUILD_VERSION_STRING", "\"" + verName + "\""
        buildConfigField "long", "BUILD_TIMESTAMP", APP_BUILD_TIMESTAMP + ""
        buildConfigField "String", "OFFICIAL_VERSION", "\"" + officialVer + "\""
        buildConfigField "int", "OFFICIAL_VERSION_CODE", officialCode + ""
        buildConfigField "int", "APP_ID", appId
        buildConfigField "String", "APP_HASH", "\"" + appHash + "\""

        externalNativeBuild {
            cmake {
                version '3.22.1'
                arguments '-DANDROID_STL=c++_static', '-DANDROID_PLATFORM=android-23' //, '-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON'
                System.getenv('PATH').split(File.pathSeparator).any { path ->
                    var file = Paths.get("${path}${File.separator}ccache${if (isWindows) ".exe" else ""}").toFile()
                    if (file.exists()) {
                        println("Using ccache ${file.getAbsolutePath()} isWindows ${isWindows}")
                        arguments += "-DCMAKE_C_COMPILER_LAUNCHER=${file.getAbsolutePath()}"
                        arguments += "-DCMAKE_CXX_COMPILER_LAUNCHER=${file.getAbsolutePath()}"
                        arguments += "-DANDROID_CCACHE=${file.getAbsolutePath()}"
                        return true
                    }
                }
                targets 'tmessages.49'
            }
        }
    }

    bundle {
        language {
            enableSplit = false
        }
    }

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

    testOptions {
        unitTests.includeAndroidResources = true
    }

    androidResources {
        noCompress += "pack"
        localeFilters += ["zz"]
    }

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

    buildTypes {
        debug {
            isDefault true
            debuggable true
            jniDebuggable true
            multiDexEnabled true
            signingConfig signingConfigs.release
        }

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

    flavorDimensions "version"

    packagingOptions {
        jniLibs {
            excludes += ['/fabric/**', '/META-INF/native-image/**']
            useLegacyPackaging true
        }
        resources {
            excludes += ['/fabric/**', '/META-INF/*.version', '/META-INF/*.kotlin_module', '/META-INF/native-image/**', '/builddef.lst', '/*.txt', '/DebugProbesKt.bin', '/okhttp3/internal/publicsuffix/NOTICE']
            excludes += ["META-INF/INDEX.LIST"]  // hutool
        }
    }

    buildFeatures {
        buildConfig true
    }

    tasks.configureEach { task ->
        if (task.name.startsWith("uploadCrashlyticsMappingFile")) {
            task.enabled = false
        } else if (task.name.contains("Crashlytics") && task.name.contains("NoGcm")) {
            task.enabled = false
        } else if (task.name.endsWith("GoogleServices") && task.name.contains("NoGcm")) {
            task.enabled = false
        } else if (task.name.contains("buildCMakeDebug") && nagram_build_args != null && nagram_build_args.contains("skip_buildCMakeDebug")) {
            task.enabled = false
        }
    }

    applicationVariants.configureEach { variant ->
        variant.outputs.configureEach { output ->
            String gramName = "Nagram"
            String first = String.format("%s-v%s(%s)", gramName, versionName, versionCode)
            String name = outputFileName.replace("TMessagesProj", first)
            name = name.replace("-release", "")
            outputFileName = name
        }
    }

    namespace "org.telegram.messenger"
}

def fcmVersion = "23.4.1"
def crashlyticsVersion = "18.6.2"

dependencies {
    implementation 'androidx.fragment:fragment:1.8.9'
    implementation "androidx.core:core-ktx:1.16.0"
    implementation "androidx.palette:palette-ktx:1.0.0"
    implementation "androidx.exifinterface:exifinterface:1.3.7"
    implementation "androidx.dynamicanimation:dynamicanimation:1.0.0"
    implementation "androidx.sharetarget:sharetarget:1.2.0"
    implementation "androidx.interpolator:interpolator:1.0.0"
    implementation 'androidx.biometric:biometric:1.1.0'
    implementation 'androidx.webkit:webkit:1.14.0'

    implementation ('com.google.android.gms:play-services-cast-framework:21.4.0') {
        exclude group: 'androidx.recyclerview', module: "recyclerview"
    }
    implementation ("androidx.mediarouter:mediarouter:1.7.0") {
        exclude group: 'androidx.recyclerview', module: "recyclerview"
    }
    implementation 'com.google.zxing:core:3.5.4'
    implementation 'com.neovisionaries:nv-websocket-client:2.14'

    implementation 'androidx.car.app:app:1.7.0'
    implementation 'androidx.car.app:app-projected:1.7.0'
    implementation 'org.nanohttpd:nanohttpd:2.3.1'

    compileOnly 'org.checkerframework:checker-qual:2.5.2'
    compileOnly 'org.checkerframework:checker-compat-qual:2.5.0'
    implementation "com.google.firebase:firebase-messaging:$fcmVersion"
    implementation "com.google.firebase:firebase-crashlytics:$crashlyticsVersion"
    implementation 'com.google.android.gms:play-services-maps:18.1.0'
    implementation 'com.google.android.gms:play-services-auth:20.4.0'
    implementation 'com.google.android.gms:play-services-vision:20.1.3'
    implementation 'com.google.android.gms:play-services-wearable:18.0.0'
    implementation 'com.google.android.gms:play-services-location:21.0.1'
    implementation 'com.google.android.gms:play-services-wallet:19.1.0'
    implementation "com.googlecode.mp4parser:isoparser:1.0.6"
    implementation 'com.stripe:stripe-android:2.0.2'
    // add for auto translate
    implementation 'com.google.mlkit:language-id:17.0.6'
    implementation 'com.android.billingclient:billing:8.0.0'
    implementation 'com.google.code.gson:gson:2.11.0'
    implementation 'com.google.guava:guava:31.1-android'
    implementation 'com.google.android.play:integrity:1.3.0'
    implementation 'com.google.android.gms:play-services-safetynet:18.0.1'

    implementation 'com.google.android.gms:play-services-mlkit-subject-segmentation:16.0.0-beta1'
    implementation 'com.google.android.gms:play-services-mlkit-image-labeling:16.0.8'

    implementation "androidx.credentials:credentials:1.6.0-alpha04"
    implementation "androidx.credentials:credentials-play-services-auth:1.6.0-alpha04"

    implementation "io.noties.markwon:core:4.6.2"
    implementation "io.noties.markwon:ext-strikethrough:4.6.2"
    implementation "io.noties.markwon:ext-tables:4.6.2"
    implementation "io.noties.markwon:html:4.6.2"
    implementation "io.noties.markwon:inline-parser:4.6.2"
    implementation("io.noties.markwon:ext-latex:4.6.2") {
        exclude group: 'ru.noties', module: 'jlatexmath-android'
    }

    api project(":TMessagesProj_Modules:media3:media-lib-exoplayer")
    api project(":TMessagesProj_Modules:media3:media-lib-exoplayer-dash")
    api project(":TMessagesProj_Modules:media3:media-lib-exoplayer-hls")
    api project(":TMessagesProj_Modules:media3:media-lib-decoder-ffmpeg")
    api project(":TMessagesProj_Modules:media3:media-lib-session")
    api project(':jlatexmath')

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

    implementation ('com.google.android.recaptcha:recaptcha:18.7.1') {
        exclude group: "com.google.crypto.tink", module: "tink-android"
    }

    testImplementation "junit:junit:4.13.2"
    testImplementation "androidx.test:core:1.5.0"
    testImplementation "org.robolectric:robolectric:4.16.1"

    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.1.5'
}
dependencies {
    implementation "androidx.browser:browser:1.8.0"
    implementation "androidx.viewpager:viewpager:1.0.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0"
    // map
    implementation "org.maplibre.gl:android-sdk:11.13.5"

    // ktor
    implementation "io.ktor:ktor-client-core:3.3.0"
    implementation "io.ktor:ktor-client-okhttp:3.3.0"
    implementation "io.ktor:ktor-client-content-negotiation:3.3.0"
    implementation "io.ktor:ktor-serialization-kotlinx-json-jvm:3.3.0"
    implementation "io.ktor:ktor-client-logging:3.3.0"

    implementation "cn.hutool:hutool-core:5.8.42"
    implementation "cn.hutool:hutool-crypto:5.8.42"
    implementation 'cn.hutool:hutool-http:5.8.42'
    // openpgp
    implementation project(":openpgp-api")

    compileOnly fileTree("libs")

    // add for undo and redo
    implementation 'org.lsposed.hiddenapibypass:hiddenapibypass:6.1'
    // add splash screen
    implementation("androidx.core:core-splashscreen:1.2.0")
    // add for emoji
    implementation 'com.jaredrummler:truetypeparser-light:1.0.0'
    // add for up
    implementation 'org.unifiedpush.android:connector:3.1.2'
    // add for copy webm and tgs to gif
    implementation "com.airbnb.android:lottie:6.4.1"
    // add for passkeys
    implementation "co.nstant.in:cbor:0.9"
}

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

sentry {
    // Disables or enables debug log output, e.g. for for sentry-cli.
    // Default is disabled.
    debug = false

    // The slug of the Sentry organization to use for uploading proguard mappings/source contexts.
    org = "teampgm"

    // The slug of the Sentry project to use for uploading proguard mappings/source contexts.
    projectName = "nagram"

    // The authentication token to use for uploading proguard mappings/source contexts.
    // WARNING: Do not expose this token in your build.gradle files, but rather set an environment
    // variable and read it into this property.
    authToken = sentry_token

    // The url of your Sentry instance. If you're using SAAS (not self hosting) you do not have to
    // set this. If you are self hosting you can set your URL here
    url = null

    // Disables or enables the handling of Proguard mapping for Sentry.
    // If enabled the plugin will generate a UUID and will take care of
    // uploading the mapping to Sentry. If disabled, all the logic
    // related to proguard mapping will be excluded.
    // Default is enabled.
    includeProguardMapping = sentry_upload

    // Whether the plugin should attempt to auto-upload the mapping file to Sentry or not.
    // If disabled the plugin will run a dry-run and just generate a UUID.
    // The mapping file has to be uploaded manually via sentry-cli in this case.
    // Default is enabled.
    autoUploadProguardMapping = sentry_upload

    // Experimental flag to turn on support for GuardSquare's tools integration (Dexguard and External Proguard).
    // If enabled, the plugin will try to consume and upload the mapping file produced by Dexguard and External Proguard.
    // Default is disabled.
    dexguardEnabled = false

    // Disables or enables the automatic configuration of Native Symbols
    // for Sentry. This executes sentry-cli automatically so
    // you don't need to do it manually.
    // Default is disabled.
    uploadNativeSymbols = sentry_upload

    // Whether the plugin should attempt to auto-upload the native debug symbols to Sentry or not.
    // If disabled the plugin will run a dry-run.
    // Default is enabled.
    autoUploadNativeSymbols = sentry_upload

    // Does or doesn't include the source code of native code for Sentry.
    // This executes sentry-cli with the --include-sources param. automatically so
    // you don't need to do it manually.
    // This option has an effect only when [uploadNativeSymbols] is enabled.
    // Default is disabled.
    includeNativeSources = false

    // Generates a JVM (Java, Kotlin, etc.) source bundle and uploads your source code to Sentry.
    // This enables source context, allowing you to see your source
    // code as part of your stack traces in Sentry.
    includeSourceContext = sentry_upload

    // Configure additional directories to be included in the source bundle which is used for
    // source context. The directories should be specified relative to the Gradle module/project's
    // root. For example, if you have a custom source set alongside 'main', the parameter would be
    // 'src/custom/java'.
    additionalSourceDirsForSourceContext = []

    // Enable or disable the tracing instrumentation.
    // Does auto instrumentation for specified features through bytecode manipulation.
    // Default is enabled.
    tracingInstrumentation {
        enabled = true

        // Specifies a set of instrumentation features that are eligible for bytecode manipulation.
        // Defaults to all available values of InstrumentationFeature enum class.
        features = [InstrumentationFeature.DATABASE, InstrumentationFeature.FILE_IO, InstrumentationFeature.OKHTTP, InstrumentationFeature.COMPOSE]

        // Enable or disable logcat instrumentation through bytecode manipulation.
        // Default is enabled.
        logcat {
            enabled = true

            // Specifies a minimum log level for the logcat breadcrumb logging.
            // Defaults to LogcatLevel.WARNING.
            minLevel = LogcatLevel.WARNING
        }

        // The set of glob patterns to exclude from instrumentation. Classes matching any of these
        // patterns in the project's sources and dependencies JARs won't be instrumented by the Sentry
        // Gradle plugin.
        //
        // Don't include the file extension. Filtering is done on compiled classes and
        // the .class suffix isn't included in the pattern matching.
        //
        // Example usage:
        // ```
        // excludes = ['com/example/donotinstrument/**', '**/*Test']
        // ```
        //
        // Only supported when using Android Gradle plugin (AGP) version 7.4.0 and above.
        excludes = []
    }

    // Enable auto-installation of Sentry components (sentry-android SDK and okhttp, timber and fragment integrations).
    // Default is enabled.
    // Only available v3.1.0 and above.
    autoInstallation {
        enabled = true

        // Specifies a version of the sentry-android SDK and fragment, timber and okhttp integrations.
        //
        // This is also useful, when you have the sentry-android SDK already included into a transitive dependency/module and want to
        // align integration versions with it (if it's a direct dependency, the version will be inferred).
        //
        // NOTE: if you have a higher version of the sentry-android SDK or integrations on the classpath, this setting will have no effect
        // as Gradle will resolve it to the latest version.
        //
        // Defaults to the latest published Sentry version.
        sentryVersion = '8.61.0'
    }

    // Disables or enables dependencies metadata reporting for Sentry.
    // If enabled, the plugin will collect external dependencies and
    // upload them to Sentry as part of events. If disabled, all the logic
    // related to the dependencies metadata report will be excluded.
    //
    // Default is enabled.
    includeDependenciesReport = true

    // Whether the plugin should send telemetry data to Sentry.
    // If disabled the plugin won't send telemetry data.
    // This is auto disabled if running against a self hosted instance of Sentry.
    // Default is enabled.
    telemetry = true
}
