import com.android.build.gradle.BaseExtension

buildscript {
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath("com.android.tools.build:gradle:8.6.0")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:2.1.0")
    }
}

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

rootProject.layout.buildDirectory.set(file("../build"))

subprojects {
    project.layout.buildDirectory.set(file("${rootProject.layout.buildDirectory.get()}/${project.name}"))
}

subprojects {
    afterEvaluate {
        val android = project.extensions.findByName("android")
        
        if (android != null) {
            
            if (android is BaseExtension) {
                android.compileSdkVersion(36)
            }

            try {
                val androidClass = android.javaClass
                
                try {
                    val namespaceProp = androidClass.getMethod("getNamespace")
                    val currentNamespace = namespaceProp.invoke(android)

                    if (currentNamespace == null) {
                        val setNamespace = androidClass.getMethod("setNamespace", String::class.java)
                        val newNamespace = project.group.toString()
                        setNamespace.invoke(android, newNamespace)
                        println("FIX: Namespace für '${project.name}' auf '$newNamespace' gesetzt.")
                    }
                } catch (e: NoSuchMethodException) {
                }
            } catch (e: Exception) {
                println("WARNUNG: Konnte Namespace für ${project.name} nicht automatisch setzen: $e")
            }
        }
    }

    project.evaluationDependsOn(":app")
}

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