import groovy.xml.Namespace
import groovy.xml.XmlParser

buildscript {
    repositories {
        google()
        mavenCentral()
        maven { url = 'https://chaquo.com/maven' }
        gradlePluginPortal()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:9.0.1'
        classpath 'com.chaquo.python:gradle:17.0.0'
        classpath 'com.google.gms:google-services:4.4.4'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:3.0.7'
    }
}

def requestedTaskNames = gradle.startParameter.taskNames.collect { it.toString() }
def androidRequested = requestedTaskNames.any { taskName ->
        taskName == 'buildAndroid' ||
            taskName.startsWith(':android-app:') ||
            taskName.toLowerCase(Locale.ROOT).contains('android') ||
            ['assembleDebug', 'testDebugUnitTest', 'installDebug'].contains(taskName)
    }

if (!androidRequested) {
    tasks.register('androidModuleInfo') {
        group = 'help'
        description = 'Explains how to build the WireShare Android module.'
        doLast {
            logger.lifecycle('WireShare Android module is configured only for Android task requests. Run ./gradlew :android-app:assembleDebug or ./gradlew buildAndroid.')
        }
    }
} else {
    apply plugin: 'com.android.application'
    apply plugin: 'com.chaquo.python'

    if (providers.gradleProperty('withGoogleServices').map { it.toBoolean() }.orElse(false).get()) {
        apply plugin: 'com.google.gms.google-services'
    }
    if (providers.gradleProperty('withCrashlytics').map { it.toBoolean() }.orElse(false).get()) {
        apply plugin: 'com.google.firebase.crashlytics'
    }

    repositories {
        google()
        mavenCentral()
        maven { url = 'https://oss.sonatype.org/content/repositories/snapshots' }
        maven {
            url = 'https://dl.frostwire.com/maven'
            content {
                includeGroup 'com.frostwire'
            }
        }
    }

    def manifestVersionCode = {
        def ns = new Namespace('http://schemas.android.com/apk/res/android', 'android')
        def xml = new XmlParser().parse(file('AndroidManifest.xml'))
        Integer.parseInt(xml.attributes()[ns.versionCode].toString())
    }

    def manifestVersionName = {
        def ns = new Namespace('http://schemas.android.com/apk/res/android', 'android')
        def xml = new XmlParser().parse(file('AndroidManifest.xml'))
        xml.attributes()[ns.versionName].toString()
    }

    ext.versionCode = manifestVersionCode()
    ext.versionName = manifestVersionName()

    android {
        namespace 'org.team_hermes.wireshare.android'
        compileSdk = 36

        defaultConfig {
            applicationId 'org.team_hermes.wireshare.android'
            versionName project.ext.versionName
            minSdkVersion 26
            targetSdkVersion 34
            multiDexEnabled true

            ndk {
                abiFilters 'arm64-v8a', 'x86_64'
            }

            python {
                def brewPython = '/opt/homebrew/bin/python3.13'
                if (new File(brewPython).exists()) {
                    buildPython brewPython
                }
                chaquopy {
                    defaultConfig {
                        version '3.13'
                    }
                }
                pip {
                    install 'yt_dlp[default]==2026.3.17'
                }
            }
        }

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_17
            targetCompatibility JavaVersion.VERSION_17
        }

        kotlin {
            jvmToolchain(17)
        }

        sourceSets {
            main {
                manifest.srcFile 'AndroidManifest.xml'
                res.srcDirs = ['res', 'apollo/res']
                aidl.srcDirs = ['src', 'apollo/src']
                assets.srcDirs = ['assets']
                java {
                    srcDir 'common/src/main/java'
                    srcDir 'apollo/src'
                    srcDir 'src/main/java'
                    exclude 'test/**'
                }
                jniLibs.srcDirs = ['libs']
                python {
                    srcDir 'src/main/python'
                }
            }
            test {
                java.srcDirs = ['src/test/java']
            }
        }

        tasks.withType(JavaCompile).configureEach {
            options.compilerArgs << '-Xlint:deprecation'
            options.compilerArgs << '-Xlint:unchecked'
        }

        signingConfigs {
            release {
                storePassword ''
                keyAlias ''
                keyPassword ''
            }
        }

        buildTypes {
            release {
                minifyEnabled true
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
                signingConfig signingConfigs.release
                multiDexKeepFile file('multidex-config.txt')
            }
            debug {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
                multiDexKeepFile file('multidex-config.txt')
            }
        }

        flavorDimensions 'classicApp'
        productFlavors {
            plus1 {
                dimension 'classicApp'
                versionCode 9090000 + project.ext.versionCode
                resValue 'string', 'application_label', 'WireShare'
            }
        }

        lint {
            abortOnError false
        }

        testOptions {
            unitTests {
                includeAndroidResources = true
                all {
                    jvmArgs '-Djava.awt.headless=true'
                }
            }
        }

        configurations {
            configureEach {
                exclude group: 'com.google.android.gms.common', module: 'play-services-measurement'
                exclude group: 'com.google.android.gms.common', module: 'play-services-base'
            }
        }

        buildFeatures {
            aidl true
            buildConfig true
            resValues true
        }
    }

    androidComponents {
        onVariants(selector().all()) { variant ->
            def suffix = "${project.ext.versionName}-b${project.ext.versionCode}-wireshare"
            def apkName = "wireshare-android-${variant.buildType}-${suffix}.apk"
            variant.outputs.each { output ->
                output.outputFileName.set(apkName)
            }
        }
    }

    dependencies {
        implementation 'org.jetbrains:annotations:26.1.0'

        implementation 'androidx.appcompat:appcompat:1.7.1'
        implementation 'androidx.browser:browser:1.10.0'
        implementation 'androidx.core:core:1.18.0'
        implementation 'androidx.exifinterface:exifinterface:1.4.2'
        implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.10.0'
        implementation 'androidx.preference:preference:1.2.1'
        implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.2.0'
        implementation 'androidx.vectordrawable:vectordrawable-animated:1.2.0'
        implementation 'com.google.android.flexbox:flexbox:3.0.0'
        implementation 'com.google.android.material:material:1.13.0'
        implementation 'com.google.code.gson:gson:2.13.2'
        implementation 'com.google.re2j:re2j:1.8'
        implementation 'com.squareup.okhttp3:okhttp:5.3.2'
        implementation 'io.coil-kt.coil3:coil:3.4.0'
        implementation 'io.coil-kt.coil3:coil-network-okhttp:3.4.0'
        implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:2.2.21'
        implementation 'androidx.work:work-runtime-ktx:2.11.2'
        implementation 'androidx.datastore:datastore-preferences:1.2.1'

        implementation 'androidx.media3:media3-exoplayer:1.10.0'
        implementation 'androidx.media3:media3-session:1.10.0'
        implementation 'androidx.media3:media3-ui:1.10.0'
        implementation 'androidx.media3:media3-common:1.10.0'

        def jlibtorrentVersion = '2.0.12.7'
        implementation "com.frostwire:jlibtorrent:${jlibtorrentVersion}"
        implementation "com.frostwire:jlibtorrent-android-arm64:${jlibtorrentVersion}"
        implementation "com.frostwire:jlibtorrent-android-x86_64:${jlibtorrentVersion}"

        if (providers.gradleProperty('withCrashlytics').map { it.toBoolean() }.orElse(false).get()) {
            implementation platform('com.google.firebase:firebase-bom:34.12.0')
            implementation 'com.google.firebase:firebase-crashlytics'
            implementation 'com.google.firebase:firebase-analytics'
        }

        testImplementation 'junit:junit:4.13.2'
        testImplementation 'org.robolectric:robolectric:4.16.1'
        testImplementation 'androidx.test:core:1.7.0'
        testImplementation 'androidx.test.ext:junit:1.3.0'
        testImplementation 'androidx.media3:media3-test-utils:1.10.0'
        testImplementation 'org.mockito:mockito-core:5.14.2'
        testImplementation 'com.squareup.okhttp3:mockwebserver:5.3.2'
    }
}
