import java.util.stream.Collectors

import static org.gradle.internal.os.OperatingSystem.current

plugins {
    id "java"
}

ext {
    mavenPluginToolsVersion = "3.15.1"
}

dependencies {
    implementation project(":htmlSanityCheck-core")
    implementation("org.apache.maven.plugin-tools:maven-plugin-tools-api:${mavenPluginToolsVersion}")
    implementation("org.apache.maven.plugin-tools:maven-plugin-annotations:${mavenPluginToolsVersion}")

    testImplementation libs.junit.jupiter
    testRuntimeOnly "org.junit.platform:junit-platform-launcher:1.12.2"
    // Explicit Launcher Version to override Gradle default
    testImplementation 'org.assertj:assertj-core:3.27.6'
}

test {
    useJUnitPlatform()
    exclude '**/*IT.class'
}

tasks.register('copyClasses', Copy) {
    dependsOn(compileJava)
    from 'build/classes/java/main'
    into 'build/maven/target/classes'
}

tasks.register('generatePom', Copy) {
    dependsOn(copyClasses)
    from 'src/main/maven'
    into 'build/maven'
    filesMatching("**/pom.*") {
        expand(version: project.version,
                mavenPluginToolsVersion: project.mavenPluginToolsVersion)
    }
}

tasks.register('generateMavenPlugin', CrossPlatformExec) {
    dependsOn(generatePom)
    // currently it seems to be the more or less only clean solution
    // to generate a plugin.xml file to use maven directly
    // if anyone has a better solution please let us know!
    buildCommand '-nsu',
            '-U',
            '-f', 'build/maven/pom.xml',
            '-s', 'settings.xml',
            'plugin:descriptor',
            '--batch-mode',
            '-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn'
}

class CrossPlatformExec extends Exec {
    void buildCommand(String... commandArgs) {
        if (current().isWindows()) {
            executable = 'cmd'
            args = ['/c', 'mvnw.cmd']
        } else {
            executable = './mvnw'
        }
        args(commandArgs.toList())
    }
}

// This ensures that other HSC modules are published to ../build/maven-repo already (in particular core)
generateMavenPlugin.configure {
    dependsOn(
            project.configurations.implementation.dependencies.withType(ProjectDependency).collect { dep ->
                project.rootProject.findProject(dep.dependencyProject.path).tasks
            }.flatten().stream()
                    .filter(task -> {
                        logger.debug("Checking '${task.name}' of '${task.project}' with class '${task.class}'")
                        task.name == 'publishMavenJavaPublicationToMyLocalRepositoryForFullIntegrationTestsRepository'
                    })
                    .collect(Collectors.toList())
    )
    onlyIf {
        gradle.taskGraph.getAllTasks().stream().anyMatch { task -> task.name == 'jar' }
    }
}

java {
    withJavadocJar()
}

jar.configure {
    dependsOn(generateMavenPlugin, "generatePomFileForMavenJavaPublication")
    doFirst {
        copy {
            from('build/maven') {
                include 'pom.properties'
            }
            into "build/classes/java/main/META-INF/maven/${project.group}/${project.name}"
        }
        copy {
            from 'build/publications/mavenJava/pom-default.xml'
            into "build/classes/java/main/META-INF/maven/${project.group}/${project.name}"
            rename { 'pom.xml' }
        }
        copy {
            from('build/maven/target/classes') {
                include '**/*.xml'
                exclude '**/*.class'
            }
            into 'build/classes/java/main'
        }
    }
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
        }
    }
}
