plugins {
    id 'java-library'
    id 'eclipse'
    id 'idea'
    id 'maven-publish'
    id 'net.neoforged.moddev' version '2.0.112'
    id 'com.diffplug.spotless' version '6.25.0'
    id 'me.modmuss50.mod-publish-plugin' version '1.0.0'
}

version = System.getenv("MI_VERSION")
        ? System.getenv("MI_VERSION")
        : "0.0.0-local"
group = "aztech"
base {
    archivesName = "Modern-Industrialization"
}

logger.lifecycle("Modern Industrialization version ${version}")

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }

    withSourcesJar()
}

repositories {
    // for KJS
    maven {
        url "https://www.cursemaven.com"
        content {
            includeGroup "curse.maven"
        }
    }
    // for AE2, JEI and Almost Unified
    maven {
        name "Modmaven"
        url "https://modmaven.dev"
        content {
            includeGroup "appeng"
            includeGroup "dev.technici4n"
            includeGroup "mezz.jei"
            includeGroup "com.almostreliable.mods"
        }
    }
    maven {
        url "https://maven.shedaniel.me"
        content {
            includeGroup "me.sargunvohra.mcmods"
            includeGroup "me.shedaniel.cloth"
            includeGroup "me.shedaniel"
            includeGroup "dev.architectury"
        }
    }
    maven {
        url "https://maven.terraformersmc.com"
        content {
            includeGroup "com.terraformersmc"
            includeGroup "dev.emi"
        }
    }
    maven {
        name 'Jitpack for MI'
        url 'https://jitpack.io'
        content {
            includeGroup "com.github.KubeJS-Mods"
            includeGroup "com.github.GabrielOlvH"
            /* For Magna */
            includeGroup "com.github.Draylar.omega-config"
            /* For KubeJS */
            includeGroup "com.github.llamalad7.mixinextras"
            // For KubeJS
            includeGroup "com.github.rtyley"
        }
    }
    // to build indrev
    maven {
        name = "CottonMC"
        url = "https://server.bbkr.space/artifactory/libs-release"
        content {
            includeGroup "io.github.cottonmc"
        }
    }
    maven {
        name = "dblsaiko"
        url = "https://maven.dblsaiko.net/"
    }
    maven {
        name = "Technici4n"
        url = "https://raw.githubusercontent.com/Technici4n/Technici4n-maven/master/"
        content {
            includeGroup "net.fabricmc.fabric-api"
            includeGroup "dev.technici4n"
            includeGroup "dev.latvian.mods"
        }
    }
    maven {
        url "https://maven.ftb.dev/releases"
        content {
            includeGroup "dev.ftb.mods"
        }
    }
    maven {
        url "https://maven.parchmentmc.net/"
        content {
            includeGroup "org.parchmentmc.data"
        }
    }
    // For the "No Indium?" mod
    maven {
        url = 'https://maven.cafeteria.dev/releases/'
        content {
            includeGroup "me.luligabi"
        }
    }
    // For KubeJS & FTBTeams/FTBQuests
    maven {
        url "https://maven.latvian.dev/releases"
        content {
            includeGroup "dev.latvian.mods"
            includeGroup "dev.ftb.mods"
        }
    }
    maven {
        url "https://maven.teamresourceful.com/repository/maven-public/"
        content {
            includeGroup "com.teamresourceful"
            includeGroup "com.teamresourceful.resourcefullib"
            includeGroup "earth.terrarium.argonauts"
            includeGroup "earth.terrarium.athena"
        }
    }
}

sourceSets {
    main {
        java {
            srcDir "src/main"
        }
        resources {
            srcDir "src/generated/resources"
        }
    }
    client {
        compileClasspath += sourceSets.main.compileClasspath
        runtimeClasspath += sourceSets.main.runtimeClasspath
        compileClasspath += sourceSets.main.output
        runtimeClasspath += sourceSets.main.output
    }
}

neoForge {
    version = project.neo_version

    mods {
        modern_industrialization {
            sourceSet sourceSets.main
        }
        modern_industrialization_with_client {
            sourceSet sourceSets.main
            sourceSet sourceSets.client
        }
    }

    runs {
        // applies to all the run configs below
        configureEach {
            loadedMods = [mods.modern_industrialization]

            // Recommended logging data for a userdev environment
            // The markers can be added/remove as needed separated by commas.
            // "SCAN": For mods scan.
            // "REGISTRIES": For firing of registry events.
            // "REGISTRYDUMP": For getting the contents of all registries.
            systemProperty 'forge.logging.markers', 'REGISTRIES'

            // Recommended logging level for the console
            // You can set various levels here.
            // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
            systemProperty 'forge.logging.console.level', 'debug'

            // Allows updates to the guide book to be watched for by GuideME.
            systemProperty 'guideme.modern_industrialization.book.sources',
                    file("src/main/resources/assets/modern_industrialization/mi_guidebook/").absolutePath
        }

        client {
            client()
            sourceSet = sourceSets.client
            loadedMods = [mods.modern_industrialization_with_client]
            // Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
            systemProperty 'forge.enabledGameTestNamespaces', "modern_industrialization"
        }

        server {
            server()
            systemProperty 'forge.enabledGameTestNamespaces', "modern_industrialization"
        }

        data {
            data()
            sourceSet = sourceSets.client
            loadedMods = [mods.modern_industrialization_with_client]
            // example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it
            // workingDirectory project.file('run-data')

            // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
            programArguments.addAll '--mod', "modern_industrialization", '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
        }

        gameTestServer {
            type = "gameTestServer"
            gameDirectory = project.file("build/gametest")
            systemProperty 'forge.enabledGameTestNamespaces', "modern_industrialization"
        }
    }

    validateAccessTransformers = true
}

configurations {
    localRuntimeOnly
    runtimeClasspath.extendsFrom localRuntimeOnly
}

dependencies {
    api jarJar("dev.technici4n:GrandPower:${project.grandpower_version}")
    implementation "org.appliedenergistics:guideme:${project.guideme_version}"

    compileOnly "mezz.jei:jei-${project.jei_minecraft_version}-neoforge-api:${project.jei_version}"
    if (project.runtime_itemlist_mod == "jei") {
        localRuntimeOnly "mezz.jei:jei-${project.jei_minecraft_version}-neoforge:${project.jei_version}"
    }

    compileOnly "me.shedaniel:RoughlyEnoughItems-neoforge:${project.rei_version}"
    compileOnly "me.shedaniel:REIPluginCompatibilities-forge-annotations:${project.rei_annotations_version}"
    if (project.runtime_itemlist_mod == "rei") {
        localRuntimeOnly "me.shedaniel:RoughlyEnoughItems-neoforge:${project.rei_version}"
    }

    compileOnly "dev.emi:emi-neoforge:${project.emi_version}+${project.emi_minecraft_version}"
    if (project.runtime_itemlist_mod == "emi") {
        localRuntimeOnly "dev.emi:emi-neoforge:${project.emi_version}+${project.emi_minecraft_version}"
        // Add JEI so that we can use EMI's builtin compat layer
        localRuntimeOnly "mezz.jei:jei-${project.jei_minecraft_version}-neoforge:${project.jei_version}"
    }

    if (!(project.runtime_itemlist_mod in ["jei", "rei", "emi", "none"])) {
        throw new GradleException("Invalid runtime_itemlist_mod value: " + project.runtime_itemlist_mod)
    }

    localRuntimeOnly compileOnly("curse.maven:jade-324717:${project.jade_file_id}")

    // TODO: compileOnly because implementation will cause datagen to crash... hopefully kubejs fixes it soon
    /*localRuntimeOnly*/ compileOnly("dev.latvian.mods:kubejs-neoforge:${project.kubejs_version}")

    localRuntimeOnly compileOnly("appeng:appliedenergistics2:${project.ae2_version}")
    compileOnly "earth.terrarium.argonauts:argonauts-neoforge-${project.argonauts_minecraft_version}:${project.argonauts_version}"
    localRuntimeOnly compileOnly("earth.terrarium.athena:athena-neoforge-${project.athena_minecraft_version}:${project.athena_version}")

    compileOnly "dev.ftb.mods:ftb-quests-neoforge:${project.ftb_quests_version}"
    compileOnly "dev.ftb.mods:ftb-teams-neoforge:${project.ftb_teams_version}"

    compileOnly "com.almostreliable.mods:almostunified-neoforge:${project.minecraft_version}-${project.au_version}:api"
}

var generateModMetadata = tasks.register("generateModMetadata", ProcessResources) {
    var replaceProperties = [
            neo_version: neo_version,
            neo_version_range: neo_version_range,
            mod_version: version,
            grandpower_version_range: grandpower_version_range,
            guideme_version_range: guideme_version_range,
            ae2_version_range: ae2_version_range,
            jei_version_range: jei_version_range,
    ]
    inputs.properties replaceProperties

    from 'src/main/templates'
    into layout.buildDirectory.dir('generated/sources/modMetadata')
    expand replaceProperties
}
sourceSets.main.resources.srcDir generateModMetadata
tasks.named("neoForgeIdeSync").configure {
    dependsOn generateModMetadata
}

tasks.withType(JavaCompile).configureEach {
    // ensure that the encoding is set to UTF-8, no matter what the system default is
    // this fixes some edge cases with special characters not displaying correctly
    // see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html
    // If Javadoc is generated, this must be specified in that task too.
    it.options.encoding = "UTF-8"
}

jar {
    from "LICENSE"
    from sourceSets.client.output
}

// configure the maven publication
publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
        }
    }

    // select the repositories you want to publish to
    repositories {
        maven {
            credentials {
                username = System.getenv("MODMAVEN_USER")
                password = System.getenv("MODMAVEN_PASSWORD")
            }
            name = "modmaven"
            url = "https://modmaven.dev/artifactory/local-releases/"
        }
    }
}

spotless {
    format 'misc', {
        target '*.gradle', '*.md', '.gitignore'

        trimTrailingWhitespace()
        indentWithSpaces()
        endWithNewline()
    }
    java {
        importOrder()

        removeUnusedImports()

        eclipse().configFile('eclipse-format.xml')

        indentWithSpaces()
        endWithNewline()
        licenseHeaderFile 'LICENSE.java'
    }
}

def releaseChannel = "stable"
def changelogContents = System.getenv("CHANGELOG") ?: "Please visit our github repository for a changelog: https://github.com/AztechMC/Modern-Industrialization/releases."
if (version.toLowerCase().contains("alpha")) {
    releaseChannel = "alpha"
    changelogContents = "THIS IS AN ALPHA RELEASE, MAKE A BACKUP BEFORE INSTALLING AND FREQUENTLY WHILE PLAYING, AND PLEASE REPORT ANY ISSUE YOU MAY FIND ON OUR ISSUE TRACKER.\n\n" + changelogContents
} else if (version.toLowerCase().contains("beta")) {
    releaseChannel = "beta"
    changelogContents = "This is a beta release. It is expected to be mostly stable, but in any case please report any issue you may find.\n\n" + changelogContents
}

// Publishing
import me.modmuss50.mpp.ReleaseType

publishMods {
    file = tasks.named("jar").flatMap { it.archiveFile }
    version = project.version
    changelog = changelogContents
    type = ReleaseType.of(releaseChannel)
    displayName = "Modern Industrialization v${project.version}"
    modLoaders = ["neoforge"]

    def shared = { platform ->
        platform.minecraftVersions.add project.minecraft_version

        platform.requires "guideme"
        platform.optional "jade", "emi", "jei"
    }

    curseforge {
        projectId = project.curseforge_project
        accessToken = providers.environmentVariable("CURSEFORGE_API_KEY")
        javaVersions.add JavaVersion.VERSION_21
        shared it
        embeds "grandpower"
        optional "roughly-enough-items"
    }

    modrinth {
        projectId = project.modrinth_project
        accessToken = providers.environmentVariable("MODRINTH_API_KEY")
        shared it
        optional "rei"
    }
}
