//noinspection GroovyAssignabilityCheck
//file:noinspection GroovyAssignabilityCheck
import proguard.gradle.ProGuardTask

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.guardsquare:proguard-gradle:7.7.0'
    }
}

plugins {
    id 'java'
    id 'idea'
    id 'java-library'
    id 'maven-publish'
    id 'com.github.johnrengelman.shadow' version '8.1.1'
    id 'net.neoforged.moddev.legacyforge' version '2.0.103'
}

// ===================== 基础配置 =====================
def enableProguard = project.hasProperty("enableProguard") && project.enableProguard.toBoolean()

tasks.named('wrapper', Wrapper).configure {
    distributionType = Wrapper.DistributionType.BIN
}

group = mod_group_id
version = "${minecraft_version}-${mod_version}"

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

base {
    archivesName = mod_id
}

println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}"

// ===================== 仓库配置 =====================
repositories {
    mavenCentral()
    maven { url = "https://libraries.minecraft.net/" }
    maven { url = "https://neoforged.forgecdn.net/releases" }
    maven { url = "https://neoforged.forgecdn.net/mojang-meta" }

    maven {
        url "https://cursemaven.com"
        content { includeGroup "curse.maven" }
    }

    maven {
        name "firstdarkdev"
        url "https://maven.firstdark.dev/snapshots"
    }
    maven {
        name = "LTD Maven"
        url = "https://nexus.bot.leisuretimedock.top/repository/maven-public/"
    }
    flatDir { dir "libs" }
}

// ===================== Forge 配置 =====================
legacyForge {
    version = "${minecraft_version}-${forge_version}"
    accessTransformers = files("src/main/templates/META-INF/accesstransformer.cfg")

    parchment {
        minecraftVersion = minecraft_version
        mappingsVersion = mapping_lasting_version
    }

    runs {
        configureEach {
            systemProperty 'forge.logging.console.level', 'debug'
            systemProperty 'forge.logging.markers', 'REGISTRIES'
            logLevel = org.slf4j.event.Level.DEBUG
        }
        client {
            client()
            systemProperty 'forge.enabledGameTestNamespaces', mod_id
        }
        clientAuth {
            devLogin = true
            client()
            systemProperty 'forge.enabledGameTestNamespaces', mod_id
        }
        server {
            server()
        }
        data {
            data()
            programArguments.addAll '--mod', mod_id, '--all',
                    '--output', file('src/generated/resources/').absolutePath,
                    '--existing', file('src/main/resources/').absolutePath
        }
    }

    mods {
        "${mod_id}" {
            sourceSet sourceSets.main
        }
    }
}

// ===================== 源码与资源 =====================
sourceSets.main.resources {
    srcDir 'src/generated/resources'
    srcDir 'src/main/resources'
}

// ===================== 编译配置 =====================
tasks.withType(JavaCompile).configureEach {
    options.encoding = 'UTF-8'
}

// ===================== 依赖 =====================
configurations {
    runtimeClasspath.extendsFrom localRuntime
    proguardLibs {
        canBeResolved = true
        canBeConsumed = false
        extendsFrom modCompileOnly
    }
}

dependencies {
    annotationProcessor ('org.spongepowered:mixin:0.8.5:processor')
    implementation(annotationProcessor("io.github.llamalad7:mixinextras-common:0.4.1"))
    modImplementation(jarJar("io.github.llamalad7:mixinextras-forge:0.4.1"))
    modImplementation("com.lowdragmc.ldlib:ldlib-forge-1.20.1:1.0.49") {
        transitive = false
    }
    modImplementation("top.r3944realms.lib39:lib39:1.20.1-${lib39_version}")
    implementation(jarJar("top.r3944realms.dg_lab.api:CommonApi:${dg_lab_version}"))
    implementation(jarJar("top.r3944realms.dg_lab:Common:${dg_lab_version}"))
}
mixin {
    add sourceSets.main, "${mod_id}.refmap.json"
    config "${mod_id}.mixins.json"
}

// ===================== 主 Jar 与混淆 =====================
jar {
    manifest {
        attributes([
                'Specification-Title'     : mod_id,
                'Specification-Vendor'    : mod_authors,
                'Specification-Version'   : '1',
                'Implementation-Title'    : project.name,
                'Implementation-Version'  : archiveVersion,
                'Implementation-Vendor'   : mod_authors,
                'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"),
                'MixinConfigs'            : "${mod_id}.mixins.json"
        ])
    }
    archiveFileName = "${mod_id}-${minecraft_version}-${mod_version}-origin.jar"

    finalizedBy 'proguard'
}

tasks.register('proguard', ProGuardTask) {
    onlyIf { enableProguard }
    dependsOn tasks.jar
    configuration 'proguard.pro'

    libraryjars "${System.getProperty('java.home')}/jmods"
    configurations.proguardLibs.resolve().each { file ->
        libraryjars file.absolutePath
    }

    def inputJar = tasks.jar.archiveFile.get().asFile
    injars inputJar
    outjars "${buildDir}/libs/[NOTUSE]${mod_id}-${minecraft_version}-${mod_version}-proguard.jar"

    doFirst {
        copy {
            from inputJar
            into "${buildDir}/libs"
            rename { "[NOTUSE]${mod_id}-${minecraft_version}-${mod_version}-origin.jar" }
        }
    }

    inputs.files tasks.jar.archiveFile
    finalizedBy 'reobfJar'
}
processResources {
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
var generateModMetadata = tasks.register("generateModMetadata", ProcessResources) {
    var replaceProperties = [
            minecraft_version        : minecraft_version,
            minecraft_version_range  : minecraft_version_range,
            forge_version            : forge_version,
            forge_version_range      : forge_version_range,
            loader_version_range     : loader_version_range,
            mod_id                   : mod_id,
            mod_name                 : mod_name,
            mod_license              : mod_license,
            mod_version              : mod_version,
            mod_authors              : mod_authors,
            mod_description          : mod_description,
            mod_credits              : mod_credits,
            lib39_version            : lib39_version,
    ]

    inputs.properties replaceProperties
    expand replaceProperties
    from "src/main/templates"
    into "build/generated/sources/modMetadata"

}

sourceSets.main.resources.srcDir generateModMetadata
legacyForge.ideSyncTask generateModMetadata

tasks.named('publish') {
    dependsOn build
}

afterEvaluate {
    tasks.named('reobfJar') {
        if (enableProguard) {
            dependsOn 'proguard'
            input = file("${buildDir}/libs/[NOTUSE]${mod_id}-${minecraft_version}-${mod_version}-proguard.jar")
        } else {
            dependsOn 'jar'
            input = tasks.jar.archiveFile.get().asFile
        }
    }
}



// ===================== 发布配置 =====================
publishing {
    publications {}

    repositories {
        maven {
            name = "local"
            url = layout.buildDirectory.dir("repo")
        }
        maven {
            name = 'LTDNexus'
            url = 'https://nexus.bot.leisuretimedock.top/repository/maven-releases/'
            credentials {
                username = System.getenv('LTDNexusUsername') ?: ''
                password = System.getenv('LTDNexusPassword') ?: ''
            }
        }
    }
}

// ===================== 构建任务依赖 =====================
tasks.named('build') {
    dependsOn sourceJar, apiSourceJar, apiJar, apiJavadocJar
}

tasks.named('clean') {
    delete fileTree(dir: "${project.projectDir}/mcmodsrepo")
}

// ===================== IDEA 支持 =====================
idea {
    module {
        downloadSources = true
        downloadJavadoc = true
    }
}
tasks.register('showTaskTree') {
    doLast {
        def showTaskDeps
        showTaskDeps = { task, prefix = '', isLast = true ->
            // 当前任务节点
            def connector = isLast ? '└── ' : '├── '
            println "${prefix}${connector}${task.name}"

            // 子任务
            def dependencies = task.getTaskDependencies().getDependencies(task).toList()
            def newPrefix = prefix + (isLast ? '    ' : '│   ')

            dependencies.eachWithIndex { dep, index ->
                def lastChild = index == dependencies.size() - 1
                showTaskDeps(dep, newPrefix, lastChild)
            }
        }

        def targetTask = tasks.findByName('build')
        if (targetTask) {
            println "构建任务依赖树:"
            showTaskDeps(targetTask, '', true)
        } else {
            println "未找到 build 任务"
        }
    }
}
