import com.android.build.gradle.LibraryExtension
import org.gradle.api.tasks.Delete
import com.android.build.gradle.BaseExtension
import org.gradle.api.JavaVersion

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

val newBuildDir: Directory =
    rootProject.layout.buildDirectory
        .dir("../../build")
        .get()
rootProject.layout.buildDirectory.value(newBuildDir)

subprojects {
    val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
    project.layout.buildDirectory.value(newSubprojectBuildDir)
}
subprojects {
    project.evaluationDependsOn(":app")
}

// Ensure older plugin modules that don't declare a `namespace` still build with AGP.
subprojects.forEach { project ->
    project.plugins.withId("com.android.library") {
        try {
            val androidExt = project.extensions.findByName("android") as? LibraryExtension
            if (androidExt != null) {
                try {
                    val current = androidExt.namespace
                    if (current.isNullOrBlank()) {
                        androidExt.namespace = "com.tasq.${project.name.replace('-', '_')}"
                    }
                } catch (e: Throwable) {
                    try {
                        androidExt.namespace = "com.tasq.${project.name.replace('-', '_')}"
                    } catch (_: Throwable) {}
                }
            }
        } catch (_: Throwable) {}
    }
}


// Ensure Kotlin JVM target matches Java compatibility to avoid mismatches in third-party modules.
// Align Java compile options to Java 17 for Android modules so Kotlin JVM target mismatch is avoided.
subprojects.forEach { project ->
    project.plugins.withId("com.android.library") {
        val androidExt = project.extensions.findByName("android") as? BaseExtension
        if (androidExt != null) {
            try {
                androidExt.compileOptions.sourceCompatibility = JavaVersion.VERSION_17
                androidExt.compileOptions.targetCompatibility = JavaVersion.VERSION_17
            } catch (_: Throwable) {}
        }
    }
    project.plugins.withId("com.android.application") {
        val androidExt = project.extensions.findByName("android") as? BaseExtension
        if (androidExt != null) {
            try {
                androidExt.compileOptions.sourceCompatibility = JavaVersion.VERSION_17
                androidExt.compileOptions.targetCompatibility = JavaVersion.VERSION_17
            } catch (_: Throwable) {}
        }
    }
}

tasks.register<Delete>("clean") {
    delete(rootProject.layout.buildDirectory)
}
