apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"
apply plugin: 'com.google.gms.google-services'
apply plugin: "io.sentry.android.gradle"
apply plugin: 'kotlin-parcelize'

// Check if this is a dev build to skip heavy processing
def isDevBuild = project.hasProperty('devBuild')

// Only apply Firebase Performance for release builds to speed up debug builds
if (!isDevBuild) {
    apply plugin: 'com.google.firebase.firebase-perf'
}

project.ext.keyFiles = [
    "prod": "keys.prod.json",
    "stg": "keys.stg.json",
    "dev": "keys.dev.json",
]

def reactNativeArchitectures() {
    def value = rootProject.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

apply from: project(':react-native-keys').projectDir.getPath() + "/RNKeys.gradle"
apply from: "../../node_modules/@sentry/react-native/sentry.gradle"

def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath()

/**
 * This is the configuration block to customize your React Native Android app.
 * By default you don't need to apply any configuration, just uncomment the lines you need.
 */
sentry {
    // Note: Sentry SDK is ALWAYS included in the app for crash reporting
    // We only disable the heavy symbol upload tasks during DEBUG builds to speed up compilation
    // Release builds (production APKs) will still upload symbols to Sentry

    // Only upload symbols for Release builds (not Debug builds during development)
    uploadNativeSymbols = gradle.startParameter.taskNames.any { it.toLowerCase().contains("release") }
    includeNativeSources = gradle.startParameter.taskNames.any { it.toLowerCase().contains("release") }

    // `@sentry/react-native` ships with compatible `sentry-android`
    // This option would install the latest version that ships with the SDK or SAGP (Sentry Android Gradle Plugin)
    // which might be incompatible with the React Native SDK
    // Enable auto-installation of Sentry components (sentry-android SDK and okhttp, timber and fragment integrations).
    // Default is enabled.
    autoInstallation {
      enabled = false
    }
}

react {
    /* Folders */
    //   The root of your project, i.e. where "package.json" lives. Default is '../..'
    // root = file("../../")
    //   The folder where the react-native NPM package is. Default is ../../node_modules/react-native
    // reactNativeDir = file("../../node_modules/react-native")
    reactNativeDir = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile()
    //   The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen
    // codegenDir = file("../../node_modules/@react-native/codegen")
    codegenDir = new File(["node", "--print", "require.resolve('@react-native/codegen/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile()

    enableBundleCompression = (findProperty('android.enableBundleCompression') ?: false).toBoolean()

    //   The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js
    // cliFile = file("../../node_modules/react-native/cli.js")
    // Use Expo CLI to bundle the app, this ensures the Metro config works correctly with Expo projects.
    cliFile = new File(["node", "--print", "require.resolve('@expo/cli', { paths: [require.resolve('expo/package.json')] })"].execute(null, rootDir).text.trim())

    /* Variants */
    //   The list of variants to that are debuggable. For those we're going to
    //   skip the bundling of the JS bundle and the assets. By default is just 'debug'.
    //   If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
    debuggableVariants = ["devDebug", "stgDebug", "prodDebug", "devDebugOptimized", "stgDebugOptimized", "prodDebugOptimized"]

    /* Bundling */
    //   A list containing the node command and its flags. Default is just 'node'.
    // nodeExecutableAndArgs = ["node"]
    //
    //   The command to run when bundling. By default is 'bundle'
    // bundleCommand = "ram-bundle"
    bundleCommand = "export:embed"
    //
    //   The path to the CLI configuration file. Default is empty.
    // bundleConfig = file(../rn-cli.config.js)
    //
    //   The name of the generated asset file containing your JS bundle
    // bundleAssetName = "MyApplication.android.bundle"
    //
    //   The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
    // entryFile = file("../js/MyApplication.android.js")
    entryFile = file(["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android", "absolute"].execute(null, rootDir).text.trim())
    //
    //   A list of extra flags to pass to the 'bundle' commands.
    //   See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
    // extraPackagerArgs = []

    /* Hermes Commands */
    //   The hermes compiler command to run. By default it is 'hermesc'
    // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
    hermesCommand = new File(["node", "--print", "require.resolve('hermes-compiler/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/hermesc/%OS-BIN%/hermesc"
    //
    //   The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
    // hermesFlags = ["-O", "-output-source-map"]

    /* Autolinking */
    autolinkLibrariesWithApp()
}

/**
 * Set this to true in release builds to optimize the app using [R8](https://developer.android.com/topic/performance/app-optimization/enable-app-optimization).
 */
def enableMinifyInReleaseBuilds = true

/**
 * The preferred build flavor of JavaScriptCore (JSC)
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US. Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+'

// Keystore props
def keystoreProps = new Properties()
    file("humand.keystore.properties").withInputStream { keystoreProps.load(it) }

android {
    ndkVersion rootProject.ext.ndkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
    compileSdk rootProject.ext.compileSdkVersion

    namespace "com.humand.demo"
    defaultConfig {
        applicationId "com.humand.demo"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionName "4.2.3"
        // Semantic versionCode — same formula used by the iOS Bitrise script so
        // iOS and Android stay in sync. Encodes major.minor.patch.iteration
        // into a single monotonically increasing integer.
        // Layout: MMM_mm_pp_iii (max: major=214, minor=99, patch=99, iteration=999).
        // `iteration` is injected from CI via -PversionIteration=<n>; defaults
        // to 1 for local builds.
        def versionParts = versionName.split("\\.")
        def major = versionParts[0].toInteger() * 10_000_000
        def minor = versionParts[1].toInteger() * 100_000
        def patch = versionParts[2].toInteger() * 1_000
        def iteration = (project.findProperty('versionIteration') ?: '1').toInteger()
        versionCode major + minor + patch + iteration
        buildConfigField "String", "REACT_NATIVE_RELEASE_LEVEL", "\"${findProperty('reactNativeReleaseLevel') ?: 'stable'}\""
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled = true
        resValue 'string', "build_config_package", "com.humand.demo"


        externalNativeBuild {
            cmake {
                cppFlags "-O3 -Wall -ffunction-sections -fdata-sections -fstack-protector-strong"
                abiFilters (*reactNativeArchitectures())
                arguments "-DANDROID_STL=c++_shared",
                        "-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON"
            }
        }

    }

    androidResources {
        noCompress += ["bundle"]
        ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:!CVS:!thumbs.db:!picasa.ini:!*~'
    }

    flavorDimensions "env"
    productFlavors {
        prod {
            dimension "env"
            applicationId 'com.humand.demo'
            manifestPlaceholders = [
                appAuthRedirectScheme: 'humand-android',
                expoChannelName: 'humand',
                usesCleartextTraffic: 'false'
            ]
        }
        stg {
            dimension "env"
            applicationId 'com.humand.demo.stg'
            manifestPlaceholders = [
                appAuthRedirectScheme: 'humand-android',
                expoChannelName: 'humand-stg',
                usesCleartextTraffic: 'true'
            ]
        }
        dev {
            dimension "env"
            applicationId 'com.humand.demo.dev'
            manifestPlaceholders = [
                appAuthRedirectScheme: 'humand-android',
                expoChannelName: 'humand-dev',
                usesCleartextTraffic: 'true'
            ]
        }
    }

    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
        release {
            storeFile file(keystoreProps.getProperty("UPLOAD_STORE_FILE"))
            storePassword keystoreProps.getProperty("UPLOAD_STORE_PASSWORD")
            keyAlias keystoreProps.getProperty("UPLOAD_KEY_ALIAS")
            keyPassword keystoreProps.getProperty("UPLOAD_KEY_PASSWORD")
        }
    }

    externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"
        }
    }

    buildFeatures {
        buildConfig true
        prefab true
    }

    buildTypes {
        debug {
            signingConfig signingConfigs.debug
            // Speed up debug builds
            crunchPngs false
            shrinkResources false
            minifyEnabled false
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.release
            shrinkResources enableMinifyInReleaseBuilds
            minifyEnabled enableMinifyInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            crunchPngs (findProperty('android.enablePngCrunchInReleaseBuilds')?.toBoolean() ?: true)
            debuggable false
        }
    }
    
    // Speed up debug builds by building only for the architecture you need
    splits {
        abi {
            reset()
            // Only enable splits for devBuild (fast development)
            // For production: splits disabled = generates only 1 universal APK with all architectures
            enable project.hasProperty('devBuild')
            if (project.hasProperty('devBuild')) {
                // For development, build only arm64-v8a (most modern devices/emulators)
                include "arm64-v8a"
                universalApk false
            }
        }
    }

    packagingOptions {
        jniLibs {
            def enableLegacyPackaging = findProperty('expo.useLegacyPackaging') ?: 'false'
            useLegacyPackaging enableLegacyPackaging.toBoolean()
        }
    }

    // Required for Stream.io SDK
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_11
    }
}

dependencies {
    implementation "androidx.multidex:multidex:2.0.1"
    // The version of react-native is set by the React Native Gradle Plugin
    implementation("com.facebook.react:react-android")

    def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";
    def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";
    def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true";

    if (isGifEnabled) {
        // For animated gif support
        implementation("com.facebook.fresco:animated-gif:${expoLibs.versions.fresco.get()}")
    }

    if (isWebpEnabled) {
        // For webp support
        implementation("com.facebook.fresco:webpsupport:${expoLibs.versions.fresco.get()}")
        if (isWebpAnimatedEnabled) {
            // Animated webp support
            implementation("com.facebook.fresco:animated-webp:${expoLibs.versions.fresco.get()}")
        }
    }
    implementation "androidx.appcompat:appcompat:1.0.0"
    
    implementation ("androidx.appcompat:appcompat:1.3.1") {
        version {
            strictly '1.3.1'
        }
    }
    implementation 'com.google.android.gms:play-services-mlkit-face-detection:17.1.0'
    implementation 'com.google.firebase:firebase-messaging-ktx:24.1.1'
    implementation 'com.google.android.gms:play-services-auth:21.4.0'
    implementation "io.github.zhongwuzw:mmkv:2.2.4"  // version is important! for 32bit devices
    implementation "androidx.work:work-runtime-ktx:2.9.0"
    implementation "androidx.localbroadcastmanager:localbroadcastmanager:1.1.0"

    implementation "androidx.emoji2:emoji2:1.5.0"
    implementation "androidx.emoji2:emoji2-bundled:1.5.0"

    implementation "io.getstream:stream-video-android-core:1.23.1"
    implementation "io.getstream:stream-video-android-ui-compose:1.23.1"

    if (hermesEnabled.toBoolean()) {
        implementation("com.facebook.react:hermes-android")
    } else {
        implementation jscFlavor
    }
}
