/*
 * Super Resolution
 * Copyright (c) 2025. 187J3X1-114514
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

import utils.ModrinthUploader

plugins {
    id 'fabric-loom' version '1.10-SNAPSHOT' apply false
    id 'net.neoforged.moddev' version '2.0.105' apply false
    id "systems.manifold.manifold-gradle-plugin" version "0.0.2-alpha"
    id 'multiversion'
    id 'multiversion-neoform'
}

allprojects {
    apply plugin: "systems.manifold.manifold-gradle-plugin"

    manifold {
        manifoldVersion = rootProject.manifold_version
    }
    group = rootProject.group
    version = rootProject.mod_version
    tasks.withType(JavaCompile) {
        options.release = versionConfig.common.javaVersion as Integer
        options.compilerArgs += ["-Xplugin:Manifold"]
        options.encoding = "UTF-8"
    }

    repositories {
        if (System.getenv().containsKey("SR_DEV")) {
            maven {
                name "minecraftdevRepository"
                url "http://127.0.0.1:8080/releases"
            }
        }
        mavenCentral()
        maven { url 'https://maven.neoforged.net' }
        maven { url 'https://maven.aliyun.com/repository/central' }
        maven { url 'https://maven.aliyun.com/repository/gradle-plugin' }
        maven { url "https://maven.architectury.dev/" }
        maven { url "https://maven.nucleoid.xyz/" }
        maven { url "https://maven.shedaniel.me/" }
        maven { url "https://maven.neoforged.net/releases" }
        maven { url "https://libraries.minecraft.net" }
        maven { url "https://maven.fabricmc.net/" }
        maven { url 'https://repo.spongepowered.org/repository/maven-public' }
        maven { url 'https://maven.parchmentmc.org/' }
        maven { url 'https://maven.blamejared.com' }
    }
    dependencies {
        annotationProcessor("systems.manifold:manifold-preprocessor:${rootProject.manifold_version}")
        configurations.configureEach {
            resolutionStrategy {
                force "org.lwjgl:lwjgl:$versionConfig.common.lwjglVersion"
                force "org.lwjgl:lwjgl-glfw:$versionConfig.common.lwjglVersion"
                force "org.lwjgl:lwjgl-opengl:$versionConfig.common.lwjglVersion"
                force "org.lwjgl:lwjgl-openal:$versionConfig.common.lwjglVersion"
                force "org.lwjgl:lwjgl-stb:$versionConfig.common.lwjglVersion"
                force "org.lwjgl:lwjgl-jemalloc:$versionConfig.common.lwjglVersion"
                force "org.lwjgl:lwjgl-tinyfd:$versionConfig.common.lwjglVersion"
                force "org.lwjgl:lwjgl-freetype:$versionConfig.common.lwjglVersion"
            }
        }
    }

}


tasks.register("uploadToModrinth") {
    doLast {
        def changelogFile = new File("CHANGELOG.md")
        if (!changelogFile.exists()) {
            throw new GradleException("CHANGELOG.md not found!")
        }

        def (currentVersion, latestChangelog) = parseChangelog(changelogFile)

        println "\n=== 最新版本更新日志 (${currentVersion}) ===\n"
        latestChangelog.each { println it }
        println "\n========================"

        def confirm = getConsoleInput("是否使用此更新日志？(Y/N): ").trim().toLowerCase()

        if (!confirm.startsWith("y")) {
            println "上传已取消"
            return
        }

        ModrinthUploader.init()
        def jarsDir = file("${projectDir}/build_jars")
        println("将要上传的文件：")
        jarsDir.eachFile { file ->
            if (file.name.startsWith("super") && file.name.endsWith(".jar")) {
                println(file.absolutePath)
            }
        }

        confirm = getConsoleInput("是否继续？(Y/N): ").trim().toLowerCase()
        if (!confirm.startsWith("y")) {
            println "上传已取消"
            return
        }
        jarsDir.eachFile { file ->
            if (file.name.startsWith("super") && file.name.endsWith(".jar")) {
                def notSucceed = true
                while (notSucceed) {
                    try {
                        ModrinthUploader.uploadFile(file, latestChangelog.join("\n"))
                        notSucceed = false
                    } catch (Exception e) {
                        e.printStackTrace()
                        confirm = getConsoleInput("上传失败，是否重试？(Y/N): ").trim().toLowerCase()
                        if (!confirm.startsWith("y")) {
                            notSucceed = false
                        }
                    }
                }
            }
        }

    }
}


static def parseChangelog(File file) {
    def versionPattern = ~/^#\s+(\d+\.\d+\.\d+(-[a-zA-Z]+(\.[\d]+)?)*)\s*$/
    def currentVersion = null
    def changelog = []
    def versionEnded = false
    def previousEmpty = false

    file.eachLine { line ->
        if (versionEnded) return

        def matcher = (line =~ versionPattern)
        if (matcher.matches()) {
            if (currentVersion == null) {
                currentVersion = matcher.group(1)
                changelog << line
            } else {
                versionEnded = true
                return
            }
        } else if (currentVersion != null) {
            if (line.trim().isEmpty()) {
                if (previousEmpty) {
                    versionEnded = true
                    return
                }
                previousEmpty = true
            } else {
                previousEmpty = false
            }
            changelog << line
        }
    }

    while (changelog.last().trim().isEmpty()) {
        changelog.removeLast()
    }

    return [currentVersion, changelog]
}

def getConsoleInput(String prompt) {
    try {
        print prompt
        def br = new BufferedReader(new InputStreamReader(System.in))
        println ""
        return br.readLine()
    } catch (IOException e) {
        throw new GradleException("无法读取用户输入", e)
    }
}