import java.io.File
import java.util.Properties

plugins {
    id("com.android.application")
    id("com.google.devtools.ksp")
    id("org.jetbrains.kotlin.plugin.compose")
}

val keystorePropertiesFile = rootProject.file("keystore.properties")
val keystoreProperties = Properties().apply {
    if (keystorePropertiesFile.exists()) {
        keystorePropertiesFile.inputStream().use(::load)
    }
}

fun signingValue(propertyName: String, envName: String): String? {
    return (keystoreProperties[propertyName] as? String)
        ?.takeIf { it.isNotBlank() }
        ?: System.getenv(envName)?.takeIf { it.isNotBlank() }
}

val releaseStoreFile = signingValue("storeFile", "RELEASE_STORE_FILE")
val releaseStorePassword = signingValue("storePassword", "RELEASE_STORE_PASSWORD")
val releaseKeyAlias = signingValue("keyAlias", "RELEASE_KEY_ALIAS")
val releaseKeyPassword = signingValue("keyPassword", "RELEASE_KEY_PASSWORD")
val hasReleaseSigning = listOf(
    releaseStoreFile,
    releaseStorePassword,
    releaseKeyAlias,
    releaseKeyPassword
).all { !it.isNullOrBlank() }

data class SupportedLocaleRow(
    val tag: String,
    val resourceQualifier: String,
    val status: String
)

val activeLocaleStatuses = setOf("complete", "partial")
val supportedLocalesCatalogFile = layout.projectDirectory.file("src/main/res/raw/supported_locales.tsv")
val defaultStringsFile = layout.projectDirectory.file("src/main/res/values/strings.xml")
val generatedLocaleResDir = layout.buildDirectory.dir("generated/res/locales")

fun parseSupportedLocaleRows(file: File): List<SupportedLocaleRow> {
    return file.readLines(Charsets.UTF_8)
        .asSequence()
        .map { it.trim() }
        .filter { it.isNotEmpty() && !it.startsWith("#") }
        .mapNotNull { line ->
            val columns = line.split('\t')
            if (columns.size < 3 || columns[0] == "tag") {
                null
            } else {
                SupportedLocaleRow(
                    tag = columns[0].trim(),
                    resourceQualifier = columns[1].trim(),
                    status = columns[2].trim().lowercase()
                )
            }
        }
        .toList()
}

fun parseStringResourceNames(file: File): Set<String> {
    val stringNamePattern = Regex("""<string\s+name="([^"]+)"""")
    return stringNamePattern.findAll(file.readText(Charsets.UTF_8))
        .map { it.groupValues[1] }
        .toSet()
}

fun rawResourceQualifierFor(row: SupportedLocaleRow): String {
    return if (row.resourceQualifier == "values") {
        "raw"
    } else {
        row.resourceQualifier.replaceFirst("values", "raw")
    }
}

val verifyLocalization = tasks.register("verifyLocalization") {
    inputs.file(supportedLocalesCatalogFile)
    inputs.file(defaultStringsFile)
    inputs.dir(layout.projectDirectory.dir("src/main/res"))

    doLast {
        val defaultStrings = parseStringResourceNames(defaultStringsFile.asFile)
        val activeRows = parseSupportedLocaleRows(supportedLocalesCatalogFile.asFile)
            .filter { it.status in activeLocaleStatuses && it.tag != "system" }

        if (activeRows.none { it.tag == "en" }) {
            throw GradleException("supported_locales.tsv must include active English fallback locale 'en'.")
        }

        activeRows
            .filterNot { it.resourceQualifier == "values" }
            .forEach { row ->
                val localizedStringsFile = layout.projectDirectory
                    .file("src/main/res/${row.resourceQualifier}/strings.xml")
                    .asFile
                if (!localizedStringsFile.exists()) {
                    throw GradleException(
                        "${row.tag} is marked '${row.status}' in supported_locales.tsv, " +
                            "but ${row.resourceQualifier}/strings.xml does not exist."
                    )
                }

                val localizedStrings = parseStringResourceNames(localizedStringsFile)
                val missing = defaultStrings - localizedStrings
                if (missing.isNotEmpty()) {
                    throw GradleException(
                        "${row.resourceQualifier}/strings.xml is missing localized strings: " +
                            missing.sorted().joinToString()
                    )
                }
            }

        activeRows
            .filter { it.status == "complete" }
            .forEach { row ->
                val privacyPolicyFile = layout.projectDirectory
                    .file("src/main/res/${rawResourceQualifierFor(row)}/privacy_policy.txt")
                    .asFile
                if (!privacyPolicyFile.exists()) {
                    throw GradleException(
                        "${row.tag} is marked 'complete' in supported_locales.tsv, " +
                            "but ${rawResourceQualifierFor(row)}/privacy_policy.txt does not exist."
                    )
                }
            }
    }
}

val generateLocaleConfig = tasks.register("generateLocaleConfig") {
    inputs.file(supportedLocalesCatalogFile)
    outputs.file(generatedLocaleResDir.map { it.file("xml/locales_config.xml") })

    doLast {
        val activeRows = parseSupportedLocaleRows(supportedLocalesCatalogFile.asFile)
            .filter { it.status in activeLocaleStatuses && it.tag != "system" }

        val outputFile = generatedLocaleResDir.get().file("xml/locales_config.xml").asFile
        outputFile.parentFile.mkdirs()
        outputFile.writeText(
            buildString {
                appendLine("""<?xml version="1.0" encoding="utf-8"?>""")
                appendLine("""<locale-config xmlns:android="http://schemas.android.com/apk/res/android">""")
                activeRows.forEach { row ->
                    appendLine("""    <locale android:name="${row.tag}" />""")
                }
                appendLine("</locale-config>")
            },
            Charsets.UTF_8
        )
    }
}

gradle.taskGraph.whenReady {
    val releaseBundleRequested = allTasks.any {
        it.path == ":app:bundleRelease" || it.name == "bundleRelease"
    }
    val releaseApkRequested = allTasks.any {
        it.path == ":app:assembleRelease" || it.name == "assembleRelease"
    }
    if ((releaseBundleRequested || releaseApkRequested) && !hasReleaseSigning) {
        throw GradleException(
            "Release signing is not configured. Fill storePassword, keyAlias, and keyPassword " +
                "in keystore.properties, or set RELEASE_STORE_FILE, RELEASE_STORE_PASSWORD, " +
                "RELEASE_KEY_ALIAS, and RELEASE_KEY_PASSWORD."
        )
    }
}

android {
    namespace = "de.softwareapp_hb.privateqrscanner"
    compileSdk = 36

    defaultConfig {
        applicationId = "de.softwareapp_hb.privateqrscanner"
        minSdk = 24
        targetSdk = 36
        versionCode = 2
        versionName = "1.0.0"
        buildConfigField("boolean", "FEATURE_PAYWALL_ENABLED", "false")

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary = true
        }
    }

    signingConfigs {
        if (hasReleaseSigning) {
            create("release") {
                storeFile = file(releaseStoreFile!!)
                storePassword = releaseStorePassword
                keyAlias = releaseKeyAlias
                keyPassword = releaseKeyPassword
            }
        }
    }

    buildTypes {
        release {
            isMinifyEnabled = true
            if (hasReleaseSigning) {
                signingConfig = signingConfigs.getByName("release")
            }
            ndk {
                debugSymbolLevel = "SYMBOL_TABLE"
            }
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
        debug {
            isMinifyEnabled = false
        }
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
        isCoreLibraryDesugaringEnabled = true
    }

    buildFeatures {
        compose = true
        buildConfig = true
    }

    packaging {
        resources {
            excludes += "/META-INF/{AL2.0,LGPL2.1}"
        }
    }
}

androidComponents {
    onVariants { variant ->
        variant.sources.res?.addStaticSourceDirectory("build/generated/res/locales")
    }
}

kotlin {
    compilerOptions {
        jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
    }
}

dependencies {
    val composeBom = platform("androidx.compose:compose-bom:2024.09.00")
    implementation(composeBom)
    androidTestImplementation(composeBom)
    androidTestImplementation("androidx.test.ext:junit:1.2.1")
    androidTestImplementation("androidx.test:runner:1.6.2")

    implementation("androidx.core:core-ktx:1.17.0")
    implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.10.0")
    implementation("androidx.lifecycle:lifecycle-runtime-compose:2.10.0")
    implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.10.0")
    implementation("androidx.activity:activity-compose:1.12.4")

    implementation("androidx.compose.ui:ui")
    implementation("androidx.compose.ui:ui-tooling-preview")
    implementation("androidx.compose.material3:material3")
    implementation("androidx.compose.material:material-icons-extended")
    implementation("com.google.android.material:material:1.13.0")
    implementation("androidx.navigation:navigation-compose:2.9.7")

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")

    implementation("androidx.camera:camera-core:1.5.3")
    implementation("androidx.camera:camera-camera2:1.5.3")
    implementation("androidx.camera:camera-lifecycle:1.5.3")
    implementation("androidx.camera:camera-view:1.5.3")

    implementation("com.google.mlkit:barcode-scanning:17.3.0")
    implementation("com.google.android.play:review:2.0.2")
    implementation("com.google.android.play:review-ktx:2.0.2")
    implementation("com.github.bitfireAT:vcard4android:7dbab269865e99eb4f46a25313d6397b51cd6ba8")

    implementation("androidx.room:room-runtime:2.8.4")
    implementation("androidx.room:room-ktx:2.8.4")
    ksp("androidx.room:room-compiler:2.8.4")

    implementation("androidx.datastore:datastore-preferences:1.2.0")
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5")

    testImplementation("junit:junit:4.13.2")
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2")

    debugImplementation("androidx.compose.ui:ui-tooling")
    debugImplementation("androidx.compose.ui:ui-test-manifest")
}

tasks.named("preBuild") {
    dependsOn(generateLocaleConfig, verifyLocalization)
}

tasks.named("check") {
    dependsOn(verifyLocalization)
}
