plugins {
    id 'maven-publish'
    id 'jacoco'
    alias catalog.plugins.envelope
    alias catalog.plugins.graalvm.native.image
    alias catalog.plugins.sambal
}
import net.woggioni.gradle.envelope.EnvelopeJarTask
import net.woggioni.gradle.envelope.EnvelopePlugin
import net.woggioni.gradle.graalvm.*
import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform

dependencies {
    implementation catalog.jwo
    implementation catalog.picocli
    implementation catalog.slf4j.simple
    implementation rootProject
    implementation project(':wcfg')
}

Property<String> mainClassName = objects.property(String.class).convention('net.woggioni.wson.cli.WsonCli')
Property<String> mainModuleName = objects.property(String.class).convention('net.woggioni.wson.cli')

envelopeJar {
    mainClass = mainClassName
    mainModule = mainModuleName
}

compileJava {
    options.compilerArgs = [
        "--patch-module",
        "net.woggioni.wson.cli=${sourceSets.main.output.asPath}"
    ]
    options.javaModuleMainClass = 'net.woggioni.wson.cli.MainKt'
    options.javaModuleVersion = project.version
}

tasks.named(NativeImagePlugin.CONFIGURE_NATIVE_IMAGE_TASK_NAME, NativeImageConfigurationTask) {
    toolchain {
        languageVersion = JavaLanguageVersion.of(25)
        vendor = JvmVendorSpec.GRAAL_VM
    }
    mainClass = mainClassName
    mainModule = mainModuleName
    mergeConfiguration = true
    modularity.inferModulePath = true
    enabled = true
    args = [
            'wcfg',
            '-f',
            '../wcfg/src/test/resources/build.wcfg',
            '-t',
            'jbon',
            '-o',
            '/dev/null'
    ]
}

nativeImage {
    toolchain {
        languageVersion = JavaLanguageVersion.of(25)
        vendor = JvmVendorSpec.GRAAL_VM
    }
    mainClass = mainClassName
    mainModule = mainModuleName
    useMusl = true
    buildStaticImage = true
    linkAtBuildTime = false
    compressExecutable = true
    compressionLevel = 6
    useLZMA = false
}

Provider<UpxTask> upxTaskProvider = tasks.named(NativeImagePlugin.UPX_TASK_NAME, UpxTask) {
}

Provider<EnvelopeJarTask> envelopeJarTaskProvider = tasks.named(EnvelopePlugin.ENVELOPE_JAR_TASK_NAME, EnvelopeJarTask.class) {
    mainModule = mainModuleName
    mainClass = mainClassName
}

artifacts {
    add('archives', upxTaskProvider)
    add('archives', envelopeJarTaskProvider)
}

publishing {
    publications {
        maven(MavenPublication) {
            artifact envelopeJar
            def host = DefaultNativePlatform.host()
            artifact(upxTaskProvider) {
                extension = "exe"
                classifier = host.operatingSystem.name + '-' + host.architecture.name
            }
        }
    }
}
