/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2026 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

val widener = extensions.create<WidenerExtension>("widener")

widener.accessWidenerFiles.setFrom(
    fileTree("src/") { include("**/*.accesswidener") }
)

val jarWidenerClasspath = rootProject.project(":AccessWidener")
    .tasks.named("shadowJar")
    .get().outputs.files

val allWidenedJars = objects.fileCollection()

project.gradle.projectsEvaluated {
    if (widener.inputJars.isEmpty) {
        logger.warn("[widener] No input JARs configured for ${project.name} — widenedJar tasks will not be registered.")
        return@projectsEvaluated
    }

    widener.inputJars.forEachIndexed { index, inputJar ->
        val taskName = if (index == 0) "widenedJar" else "widenedJar$index"
        val outputFile = layout.buildDirectory
            .file("widened/${inputJar.nameWithoutExtension}-widened.jar")

        val task = tasks.register<JavaExec>(taskName) {
            description = "Produces a widened copy of ${inputJar.name} for compile-time use."
            group = "widener"

            inputs.file(inputJar)
            inputs.files(widener.accessWidenerFiles)
            outputs.file(outputFile)

            classpath = jarWidenerClasspath
            mainClass.set("de.steamwar.Main")

            dependsOn(rootProject.project(":AccessWidener").tasks.named("shadowJar"))

            doFirst {
                args = buildList {
                    add(inputJar.absolutePath)
                    add(outputFile.get().asFile.absolutePath)
                    addAll(widener.accessWidenerFiles.map { it.absolutePath })
                }
            }
        }

        allWidenedJars.from(task)
    }

    tasks.named("compileJava") {
        dependsOn(allWidenedJars)
    }
}

project.dependencies {
    add("compileOnly", project.fileTree("build/widened"))
}
