plugins {
    alias(libs.plugins.android.application)
}

def enableAbiSplits = (project.findProperty("enableAbiSplits") ?: "true").toBoolean()

android {
    namespace = 'de.schliweb.makeacopy'
    compileSdk = 36

    ndkVersion = '28.0.13004108'

    defaultConfig {
        applicationId "de.schliweb.makeacopy"
        minSdk = 29
        targetSdk = 36
        versionCode 10704
        versionName "1.7.4"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        // Add a note about OpenCV being built from source
        buildConfigField "String", "OPENCV_VERSION", "\"4.12.0\""
    }

    dependenciesInfo {
        // Disables the inclusion of dependency metadata in the APK,
        // required for F-Droid to comply with its focus on privacy and transparency.
        // Dependency metadata is unnecessary and could expose additional information.
        includeInApk = false
        // Disables the inclusion of dependency metadata in Android App Bundles as well.
        includeInBundle = false
    }

    packaging {
        jniLibs {
            useLegacyPackaging = false
            // New API (replaces deprecated doNotStrip):
            // keep the symbols → AGP will not run its strip step,
            // preserving our staged, deterministic lib exactly.
            keepDebugSymbols += ["lib/**/libopencv_java4.so"]
        }
        dex {
            useLegacyPackaging = false
        }
    }

    signingConfigs {
        release {
            def myStorePassword = project.findProperty("SIGNING_STORE_PASSWORD") ?: System.getenv("SIGNING_STORE_PASSWORD")
            def myKeyAlias = project.findProperty("SIGNING_KEY_ALIAS") ?: System.getenv("SIGNING_KEY_ALIAS")
            def myKeyPassword = project.findProperty("SIGNING_KEY_PASSWORD") ?: System.getenv("SIGNING_KEY_PASSWORD")
            if (myStorePassword && myKeyAlias && myKeyPassword) {
                storeFile file('keystore.jks')
                storePassword myStorePassword
                keyAlias myKeyAlias
                keyPassword myKeyPassword
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled = true
            shrinkResources = true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            // Only use signing config when available (GitHub Actions)
            // F-Droid will sign with their own keys
            if (project.hasProperty('SIGNING_KEY_ALIAS') && System.getenv('SIGNING_STORE_PASSWORD')) {
                signingConfig signingConfigs.release
            }
        }
    }

    splits {
        abi {
            enable = enableAbiSplits
            reset()
            def abisEnv = System.getenv("ABIS")
            def abisProp = (project.findProperty("ABIS") ?: project.findProperty("abis"))
            def abisList = ((abisEnv ?: abisProp) ?: "arm64-v8a armeabi-v7a x86_64 x86")
                    .trim()
                    .split(/[,\s]+/) as List<String>
            println "Gradle ABI splits: ${abisList}"
            abisList.each { include it }

            universalApk = false
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }
    buildFeatures {
        viewBinding = true
        buildConfig = true
    }

    sourceSets {
        main {
            assets.srcDirs = [
                    'src/main/assets',
                    layout.buildDirectory.dir("generated/assets/licenses").get().asFile
            ]
            jniLibs.srcDirs = ['src/main/jniLibs']
        }
    }
}
dependencies {

    implementation libs.appcompat
    implementation libs.material
    implementation libs.constraintlayout
    implementation libs.lifecycle.livedata.ktx
    implementation libs.lifecycle.viewmodel.ktx
    implementation libs.navigation.fragment
    implementation libs.navigation.ui
    implementation libs.activity


    // JSON serialization for registry
    implementation libs.gson

    // Lombok dependency
    compileOnly libs.lombok
    annotationProcessor libs.lombok

    // CameraX dependencies
    implementation libs.camerax.core
    implementation libs.camerax.camera2
    implementation libs.camerax.lifecycle
    implementation libs.camerax.view

    // Tesseract OCR dependency
    implementation libs.tesseract

    // Onnx-Runtime dependency
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    // PdfBox-Android dependency
    implementation libs.pdfbox.android
    implementation libs.exifinterface

    testImplementation libs.junit
    androidTestImplementation(libs.ext.junit) {
        exclude group: 'org.hamcrest', module: 'hamcrest-core'
        exclude group: 'org.hamcrest', module: 'hamcrest-library'
    }
    androidTestImplementation(libs.espresso.core) {
        exclude group: 'org.hamcrest', module: 'hamcrest-core'
        exclude group: 'org.hamcrest', module: 'hamcrest-library'
    }
    androidTestImplementation(libs.test.rules) {
        exclude group: 'org.hamcrest', module: 'hamcrest-core'
        exclude group: 'org.hamcrest', module: 'hamcrest-library'
    }
    // fragment-testing must be in the target (debug) APK to provide EmptyFragmentActivity
    debugImplementation(libs.fragment.testing)
    // Align Hamcrest to a single modern version to avoid duplicate classes
    androidTestImplementation 'org.hamcrest:hamcrest:2.2'
    androidTestImplementation libs.awaitility
}



tasks.register("copyNotices", Sync) {
    from("$rootDir/NOTICE", "$rootDir/LICENSE")
    into(layout.buildDirectory.dir("generated/assets/licenses"))
}

tasks.named("preBuild").configure {
    dependsOn("copyNotices")
}

androidComponents {
    onVariants(selector().withBuildType("release")) { variant ->
        // Exclude test PDFs from release APK/AAB packaging
        variant.packaging.resources.excludes.add("assets/test_pdfs/**")
    }

    // Assign per-ABI versionCode: baseVersionCode * 10 + abiCode
    onVariants(selector().all()) { variant ->
        def baseCode = (project.android.defaultConfig.versionCode ?: 1)
        def abiCodes = [
                "armeabi-v7a": 1,
                "arm64-v8a" : 2,
                "x86"       : 3,
                "x86_64"    : 4
        ]
        variant.outputs.each { output ->
            def abiFilter = output.filters.find { it.filterType == com.android.build.api.variant.FilterConfiguration.FilterType.ABI }
            if (abiFilter != null) {
                def abi = abiFilter.identifier
                def code = abiCodes.get(abi, 0)
                output.versionCode.set(baseCode * 10 + code)
            } else {
                // For non-ABI outputs (e.g., no splits) keep deterministic ordering
                output.versionCode.set(baseCode * 10)
            }
        }
    }
}


// Ensure Java compiler shows deprecation and unchecked warnings in builds
// This helps us review all deprecated APIs in use during the build
// and aligns with the task to verify deprecation warnings.
tasks.withType(JavaCompile).configureEach {
    options.deprecation = true
    options.compilerArgs += [
            '-Xlint:deprecation',
            '-Xlint:unchecked'
    ]
}
