import java.util.*

plugins {
    kotlin("jvm") version "2.3.20"
    id("dev.architectury.loom")
    id("architectury-plugin")
    id("me.modmuss50.mod-publish-plugin")
    id("com.gradleup.shadow")
}

val minecraft = stonecutter.current.version
val loader = loom.platform.get().name.lowercase()

fun minecraftVersionToNum(ver: String): Int {
    val parts = ver.split(".")
    if(parts.size == 2) {
        // 26.1 and above
        return parts[0].toInt() * 10000 + parts[1].toInt()
    }
    return parts[1].toInt() * 100 + parts[2].toInt()
}

version = "${mod.version}+$minecraft"
group = mod.group
base {
    archivesName.set("${mod.id}-$loader")
}

architectury.common(stonecutter.tree.branches.mapNotNull {
    if (stonecutter.current.project !in it) null
    else it.prop("loom.platform")
})

repositories {
    maven("https://maven.neoforged.net/releases/")

    //modmenu
    maven("https://maven.terraformersmc.com/")
    //placeholder api (modmenu depencency)
    maven("https://maven.nucleoid.xyz/")
    maven {
        name = "Kotlin for Forge"
        setUrl("https://thedarkcolour.github.io/KotlinForForge/")
    }
}
dependencies {
    minecraft("com.mojang:minecraft:$minecraft")
    mappings(loom.officialMojangMappings())

    var archversion = "idk"
    when(minecraft) { // NOTE: add more entries if you want to add more versions
        "1.20.1" -> archversion = "9.2.14"
        "1.20.4" -> archversion = "11.1.17"
        "1.21.1" -> archversion = "13.0.8"
        "1.21.9" -> archversion = "18.0.5"
        else     -> archversion = "19.0.1" 
    }

    // modImplementation("dev.architectury:architectury:$rootProject.architectury_api_version")
    // modImplementation("dev.architectury:architectury:${archversion}")
    modImplementation("dev.architectury:architectury:${archversion}")
    if (loader == "fabric") {
        modImplementation("net.fabricmc:fabric-loader:${mod.dep("fabric_loader")}")
//        mappings("net.fabricmc:yarn:$minecraft+build.${mod.dep("yarn_build")}:v2")
        modImplementation("com.terraformersmc:modmenu:${mod.dep("modmenu_version")}")
        //some features (like automatic resource loading from non vanilla namespaces) work only with fabric API installed
        //for example translations from assets/modid/lang/en_us.json won't be working, same stuff with textures
        //but we keep runtime only to not accidentally depend on fabric's api, because it doesn't exist in neo/forge
        modRuntimeOnly("net.fabricmc.fabric-api:fabric-api:${mod.dep("fabric_version")}")
        modImplementation("net.fabricmc:fabric-language-kotlin:1.13.10+kotlin.2.3.20")
        modApi("dev.architectury:architectury-fabric:${archversion}")
        fun getTeamRebornEnergy(): String {
            val curVer = minecraftVersionToNum(minecraft)
            if (curVer < minecraftVersionToNum("1.20.5")) { return "3.0.0" }
            if (curVer < minecraftVersionToNum("1.21.0")) { return "4.0.0" }
            if (curVer < minecraftVersionToNum("1.21.5")) { return "4.1.0" }
            if (curVer < minecraftVersionToNum("26.1")) { return "4.2.0" }
            return "5.0.0"
        }
        modApi("teamreborn:energy:${getTeamRebornEnergy()}")
    }
    if (loader == "forge") {
        "forge"("net.minecraftforge:forge:${minecraft}-${mod.dep("forge_loader")}")
        //implementation("thedarkcolour:kotlinforforge:1.16.0")
//        mappings("net.fabricmc:yarn:$minecraft+build.${mod.dep("yarn_build")}:v2")

        modApi("dev.architectury:architectury-forge:${archversion}")
        "io.github.llamalad7:mixinextras-forge:${mod.dep("mixin_extras")}".let {
            implementation(it)
            include(it)
        }
    }
    if (loader == "neoforge") {
        "neoForge"("net.neoforged:neoforge:${mod.dep("neoforge_loader")}")
//        mappings(loom.layered {
//            mappings("net.fabricmc:yarn:$minecraft+build.${mod.dep("yarn_build")}:v2")
//            mod.dep("neoforge_patch").takeUnless { it.startsWith('[') }?.let {
//                mappings("dev.architectury:yarn-mappings-patch-neoforge:$it")
//            }
//        })

        if (minecraft=="1.21.9" || minecraft=="1.21.11") modApi("dev.architectury:architectury-neoforge:${archversion}")
        else modApi("dev.architectury:architectury-forge:${archversion}") // NOTE: this could be wrong
        implementation("thedarkcolour:kotlinforforge-neoforge:6.0.0")

    }
}
buildscript {
    dependencies {
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0")
    }
}
loom {
    accessWidenerPath = rootProject.file("src/main/resources/neocomputers.accesswidener")

    decompilers {
        get("vineflower").apply { // Adds names to lambdas - useful for mixins
            options.put("mark-corresponding-synthetics", "1")
        }
    }
    if (loader == "forge") {
        forge.mixinConfigs(
            "neocomputers-common.mixins.json",
            "neocomputers-forge.mixins.json",
        )
    }
}

val localProperties = Properties()
val localPropertiesFile = rootProject.file("local.properties")
if (localPropertiesFile.exists()) {
    localProperties.load(localPropertiesFile.inputStream())
}
publishMods {
    val modrinthToken = localProperties.getProperty("publish.modrinthToken", "")
    val curseforgeToken = localProperties.getProperty("publish.curseforgeToken", "")


    file = project.tasks.remapJar.get().archiveFile
    dryRun = modrinthToken == null || curseforgeToken == null

    displayName = "${mod.name} ${loader.replaceFirstChar { it.uppercase() }} ${property("mod.mc_title")}-${mod.version}"
    version = mod.version
    changelog = rootProject.file("CHANGELOG.md").readText()
    type = BETA

    modLoaders.add(loader)

    val targets = property("mod.mc_targets").toString().split(' ')
    modrinth {
        projectId = property("publish.modrinth").toString()
        accessToken = modrinthToken
        targets.forEach(minecraftVersions::add)
        if (loader == "fabric") {
            requires("fabric-api")
            requires("fabric-language-kotlin")
            optional("modmenu")
        }
        if (loader == "neoforge") {
            requires("kotlinforforge-neoforge")
        }
    }

    curseforge {
        projectId = property("publish.curseforge").toString()
        accessToken = curseforgeToken.toString()
        targets.forEach(minecraftVersions::add)
        if (loader == "fabric") {
            requires("fabric-api")
            requires("fabric-language-kotlin")
            optional("modmenu")
        }
        if (loader == "neoforge") {
            requires("kotlinforforge-neoforge")
        }
    }
}

java {
    withSourcesJar()
    val java = if (stonecutter.eval(minecraft, ">=1.20.5")) JavaVersion.VERSION_21 else JavaVersion.VERSION_17
    targetCompatibility = java
    sourceCompatibility = java
}

kotlin {
    val java = if (stonecutter.eval(minecraft, ">=1.20.5")) 21 else 17
    jvmToolchain(java)
}

val shadowBundle: Configuration by configurations.creating {
    isCanBeConsumed = false
    isCanBeResolved = true
}

tasks.shadowJar {
    configurations = listOf(shadowBundle)
    archiveClassifier = "dev-shadow"
}

tasks.remapJar {
    injectAccessWidener = true
    input = tasks.shadowJar.get().archiveFile
    archiveClassifier = null
    dependsOn(tasks.shadowJar)
}

tasks.jar {
    archiveClassifier = "dev"
}

val buildAndCollect = tasks.register<Copy>("buildAndCollect") {
    group = "versioned"
    description = "Must run through 'chiseledBuild'"
    from(tasks.remapJar.get().archiveFile, tasks.remapSourcesJar.get().archiveFile)
    into(rootProject.layout.buildDirectory.file("libs/${mod.version}/$loader"))
    dependsOn("build")
}

if (stonecutter.current.isActive) {
    rootProject.tasks.register("buildActive") {
        group = "project"
        dependsOn(buildAndCollect)
    }

    rootProject.tasks.register("runActive") {
        group = "project"
        dependsOn(tasks.named("runClient"))
    }
}

tasks.processResources {
    properties(
        listOf("fabric.mod.json"),
        "id" to mod.id,
        "name" to mod.name,
        "version" to mod.version,
        "minecraft" to mod.prop("mc_dep_fabric")
    )
    properties(
        listOf("META-INF/mods.toml", "pack.mcmeta"),
        "id" to mod.id,
        "name" to mod.name,
        "version" to mod.version,
        "minecraft" to mod.prop("mc_dep_forgelike")
    )
    properties(
        listOf("META-INF/neoforge.mods.toml", "pack.mcmeta"),
        "id" to mod.id,
        "name" to mod.name,
        "version" to mod.version,
        "minecraft" to mod.prop("mc_dep_forgelike")
    )
}

tasks.build {
    group = "versioned"
    description = "Must run through 'chiseledBuild'"
}