plugins {
    id 'java-library'
    id 'idea'
    id 'net.neoforged.moddev' version '1.0.17'
    id("com.modrinth.minotaur") version '2.+'
    id("com.matthewprenger.cursegradle") version '1.4.0'
}

version = '3.4'
group = 'thedarkcolour.exdeorum'
base {
    archivesName = 'exdeorum'
}

java.toolchain.languageVersion = JavaLanguageVersion.of(21)
java.toolchain.vendor = JvmVendorSpec.JETBRAINS
java.withSourcesJar()

neoForge {
    version = neo_version

    parchment {
        mappingsVersion = project.parchment_mappings_version
        minecraftVersion = project.parchment_minecraft_version
    }

    accessTransformers = project.files('src/main/resources/META-INF/accesstransformer.cfg')

    runs {
        configureEach {
            logLevel = org.slf4j.event.Level.DEBUG
            jvmArgument '-XX:+AllowEnhancedClassRedefinition'
        }

        client {
            client()
        }

        server {
            server()
            gameDirectory.set(project.layout.projectDirectory.dir('run/server'))
            programArgument '--nogui'
        }

        data {
            data()
            // instead of using --all, skip file check validation
            programArguments.addAll('--server', '--client', '--dev', '--reports')
            programArguments.addAll ('--mod', 'exdeorum', '--output', file('src/generated/resources/').absolutePath, '--existing', file('src/main/resources/').absolutePath)
        }
    }

    mods {
        "${mod_id}" {
            sourceSet(sourceSets.main)
        }
        coremod {
            dependency project(':coremod')
        }
    }
}

// Include resources generated by data generators.
sourceSets.main.resources { srcDir 'src/generated/resources' }

repositories {
    mavenCentral()
    maven {
        name = 'McJty maven'
        url = 'https://maven.k-4u.nl'
        content { includeGroup 'mcjty.theoneprobe' }
    }
    maven {
        name = 'jei'
        url = 'https://maven.blamejared.com/'
        content { includeGroup "mezz.jei" }
    }
    maven {
        name = 'rei'
        url = "https://maven.shedaniel.me"
    }
    maven {
        name = 'Architectury API'
        url = "https://maven.architectury.dev"
        content { includeGroup "dev.architectury" }
    }
    maven {
        name = 'KubeJS and Rhino'
        url = "https://maven.saps.dev/minecraft"
        content {
            includeGroup "dev.latvian.mods"
            includeGroup "dev.latvian.apps"
        }
    }
    maven {
        name = 'ModKit'
        url 'https://jitpack.io'
        content { includeGroup 'com.github.thedarkcolour' }
    }
    maven {
        name = 'TerraformersMC'
        url = 'https://maven.terraformersmc.com'
    }
    maven {
        name = "Modrinth"
        url = "https://api.modrinth.com/maven"
        content {
            includeModule("maven.modrinth", "oculus")
            includeModule("maven.modrinth", "embeddium")
        }
    }
    maven {
        url "https://cursemaven.com"
        content {
            includeGroup "curse.maven"
        }
    }
    // Required for KubeJS
    maven {
        url 'https://jitpack.io'
        content {
            includeGroup "com.github.rtyley"
        }
    }
}

dependencies {
    // TOP OPTIONAL
    compileOnly("mcjty.theoneprobe:theoneprobe:1.21_neo-${top_version}") {
        transitive = false
    }
    // JADE OPTIONAL
    compileOnly("curse.maven:jade-324717:5109393")
    // JEI OPTIONAL
    compileOnly("mezz.jei:jei-${mc_version}-neoforge-api:${jei_version}")
    runtimeOnly("mezz.jei:jei-${mc_version}-neoforge:${jei_version}")
    // REI OPTIONAL todo add
    compileOnly("me.shedaniel:RoughlyEnoughItems-forge:${rei_version}")
    compileOnly("me.shedaniel.cloth:cloth-config-neoforge:${cloth_config_version}")
    // EMI OPTIONAL
    compileOnly("dev.emi:emi-neoforge:${emi_version}+${mc_version}:api")
    //runtimeOnly("dev.emi:emi-neoforge:${emi_version}+${mc_version}")
    //implementation("curse.maven:reipc-521393:4837449")
    // KubeJS OPTIONAL
    implementation("dev.architectury:architectury-neoforge:${architectury_version}")
    implementation("dev.latvian.mods:rhino:${rhino_version}")
    implementation("dev.latvian.mods:kubejs-neoforge:${kubejs_version}")

    // ModKit DEV ONLY
    implementation('com.github.thedarkcolour:ModKit:81a0889b26')

    // Core mod
    implementation(jarJar(project(':coremod')))

    // Oculus + Embeddium OPTIONAL
    compileOnly('maven.modrinth:oculus:1.20.1-1.6.9')
    compileOnly('maven.modrinth:embeddium:0.3.9+mc1.20.4')

    // testing
    //implementation("curse.maven:allthecompressed-514045:4938351")
    compileOnly("curse.maven:alltheores-405593:5500624")
    //implementation("curse.maven:inventorysorter-240633:4655091")
    //implementation("curse.maven:cyclic-239286:4994392")
    //implementation("curse.maven:flib-661261:4724762")
}

tasks.withType(ProcessResources).configureEach {
    var replaceProperties = [
            mc_version: mc_version,
            mod_version: version,
            neo_version_range: neo_version_range,
            loader_version_range: loader_version_range
    ]
    inputs.properties replaceProperties

    filesMatching(['META-INF/neoforge.mods.toml']) {
        expand replaceProperties
    }
}

tasks.withType(JavaCompile).configureEach {
    options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
}

idea {
    module {
        downloadSources = true
        downloadJavadoc = true
    }
}

if (System.getenv("CURSEFORGE_TOKEN")) {
    curseforge {
        apiKey = System.getenv("CURSEFORGE_TOKEN")

        project {
            id = "901420"
            changelogType = "markdown"
            changelog = getChangelog(project.version)

            releaseType = "release"

            addGameVersion(mc_version)
            addGameVersion("NeoForge")
            addGameVersion("Java 21")

            mainArtifact(jar.archiveFile) {
                displayName = "Ex Deorum ${project.version}"
            }
        }
    }
}

modrinth {
    token = System.getenv("MODRINTH_TOKEN")
    projectId = "WP0FLyzv"
    versionName = "Ex Deorum ${project.version}"
    gameVersions = [mc_version]
    loaders = ["neoforge"]
    changelog = getChangelog(project.version)

    uploadFile = jar
    additionalFiles.add(sourcesJar)
}

static def getChangelog(Object version) {
    version = version.toString()

    def file = new File('changelog.md')
    if (!file.exists()) {
        return "Changelog file not found"
    }

    // Relies on the changelog block being "##blahblahblah_VERSION" where _ is a space
    def content = file.text.normalize().split("##.* ")

    for (final def chunk in content) {
        if (chunk.isEmpty()) continue

        def lineTerminatorIndex = chunk.findIndexOf { c -> c == '\n' || c == '\r' }
        def versionString = chunk.substring(0, lineTerminatorIndex)

        if (versionString == version) {
            return "## Ex Deorum $version\n" + chunk.substring(lineTerminatorIndex + 1)
        }
    }

    // Fallback in case this fails
    return "Ex Deorum Update ${version}"
}
