plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.kotlin.android)
    alias(libs.plugins.kotlin.compose)
    alias(libs.plugins.hilt)
    alias(libs.plugins.ksp)
    alias(libs.plugins.kotlin.serialization)
}

// ── Sentry DSN — single source of truth is Azure Key Vault (SPEC §16.1) ────────
// The DSN is fetched from `kv-cbb-shared-prod/sentry-dsn-android` at configuration
// time and injected into BuildConfig.SENTRY_DSN. It is NEVER committed to the repo.
//
// Graceful degradation (mandatory): if the secret cannot be fetched — no `az` CLI,
// not authenticated, offline, or KV unreachable — this returns an empty string and
// the build proceeds. An empty DSN means crash reporting is a no-op at runtime, so a
// developer without vault access can still build and run; reporting simply stays off
// (which is the opt-in default state anyway).
//
// Override for CI/special cases via -PsentryDsn=... or ORG_GRADLE_PROJECT_sentryDsn.
fun resolveSentryDsn(): String {
    (project.findProperty("sentryDsn") as String?)?.takeIf { it.isNotBlank() }?.let { return it }
    return try {
        val execOutput = providers.exec {
            commandLine(
                "az", "keyvault", "secret", "show",
                "--vault-name", "kv-cbb-shared-prod",
                "--name", "sentry-dsn-android",
                "--query", "value", "-o", "tsv",
            )
            isIgnoreExitValue = true
        }
        if (execOutput.result.get().exitValue == 0) {
            execOutput.standardOutput.asText.get().trim()
        } else {
            ""
        }
    } catch (e: Exception) {
        // az not installed / not on PATH / any failure → disabled, never fatal
        ""
    }
}

val sentryDsn: String = resolveSentryDsn()
if (sentryDsn.isBlank()) {
    logger.lifecycle("Sentry DSN not resolved from Key Vault — crash reporting will be DISABLED in this build.")
}

android {
    namespace   = "com.coldboreballisticsllc.scopedope"
    compileSdk  = 35

    defaultConfig {
        applicationId  = "com.coldboreballisticsllc.scopedope"
        minSdk         = 31
        targetSdk      = 35
        versionCode    = 13
        versionName    = "0.9.6-beta4"

        buildConfigField("long", "BUILD_TIMESTAMP", "${System.currentTimeMillis()}L")

        // Sentry DSN injected from Key Vault (empty = crash reporting disabled). See top of file.
        buildConfigField("String", "SENTRY_DSN", "\"$sentryDsn\"")

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            isMinifyEnabled   = true
            isShrinkResources = true
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }

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

    kotlinOptions {
        jvmTarget = "17"
    }

    buildFeatures {
        compose      = true
        buildConfig  = true
    }

    sourceSets {
        getByName("main") {
            assets.srcDirs(rootProject.file("shared/assets").path)
        }
    }
}

ksp {
    arg("room.schemaLocation", "$projectDir/schemas")
    arg("room.incremental", "true")
}

dependencies {
    implementation(project(":shared:ballistics"))
    implementation(libs.androidx.core.ktx)
    implementation(libs.androidx.lifecycle.runtime.ktx)
    implementation(libs.androidx.lifecycle.viewmodel.compose)
    implementation(libs.androidx.activity.compose)

    // Compose
    implementation(platform(libs.androidx.compose.bom))
    implementation(libs.androidx.compose.ui)
    implementation(libs.androidx.compose.ui.graphics)
    implementation(libs.androidx.compose.ui.tooling.preview)
    implementation(libs.androidx.compose.material3)
    implementation(libs.androidx.compose.material.icons.extended)
    debugImplementation(libs.androidx.compose.ui.tooling)
    debugImplementation(libs.androidx.compose.ui.test.manifest)

    // Navigation
    implementation(libs.androidx.navigation.compose)

    // Room
    implementation(libs.androidx.room.runtime)
    implementation(libs.androidx.room.ktx)
    ksp(libs.androidx.room.compiler)

    // Hilt
    implementation(libs.hilt.android)
    ksp(libs.hilt.compiler)
    implementation(libs.hilt.navigation.compose)

    // DataStore
    implementation(libs.androidx.datastore.preferences)

    // Coroutines
    implementation(libs.kotlinx.coroutines.android)

    // Serialization (.dope file format)
    implementation(libs.kotlinx.serialization.json)

    // Google Fonts (IBM Plex Mono + Inter via Play Services provider)
    implementation(libs.androidx.compose.ui.text.google.fonts)

    // Play In-App Review
    implementation(libs.play.review.ktx)

    // Sentry — crash reporting (opt-in, OFF by default; consent-gated init; SPEC §16.1).
    // Exclude transitive modules incompatible with our privacy posture / unused by this app:
    //  - sentry-android-replay: Session Replay records the screen (could capture ballistic
    //    data / on-screen content) — categorically excluded.
    //  - sentry-android-ndk / sentry-native-ndk: native minidump capture. The app is pure
    //    Kotlin/JVM (no NDK code), and minidumps can capture raw memory — excluded as a
    //    PII-surface and as dead weight.
    implementation(libs.sentry.android) {
        exclude(group = "io.sentry", module = "sentry-android-replay")
        exclude(group = "io.sentry", module = "sentry-android-ndk")
        exclude(group = "io.sentry", module = "sentry-native-ndk")
    }

    // Unit tests
    testImplementation(libs.junit)
    testImplementation(libs.kotlinx.coroutines.test)
}
