import net.earthcomputer.clientcommands.buildscript.CheckLanguageFilesTask
import net.earthcomputer.clientcommands.buildscript.GenerateBuildInfoTask
import net.fabricmc.loom.task.prod.ClientProductionRunTask

plugins {
	id 'fabric-loom' version "${loom_version}"
	id 'maven-publish'
	id 'com.modrinth.minotaur' version '2.+'
	id 'com.github.breadmoirai.github-release' version '2.4.1'
	id 'checkstyle'
}

base {
	archivesName = project.archives_base_name
	version = project.mod_version
	group = project.maven_group
}

sourceSets {
	codeGen
}

configurations {
	includedLibrary
	implementation.extendsFrom includedLibrary
}

repositories {
	maven {
		url = 'https://maven.seedfinding.com'
	}
	maven {
		url = 'https://maven.latticg.com'
	}
	maven {
		url = 'https://maven.xpple.dev/maven2'
	}
	maven {
		url = "https://pkgs.dev.azure.com/djtheredstoner/DevAuth/_packaging/public/maven/v1"
	}
	maven {
		url = "https://maven.parchmentmc.org"
	}
}

loom {
	accessWidenerPath = file('src/main/resources/clientcommands.aw')
}

dependencies {
	minecraft "com.mojang:minecraft:${project.minecraft_version}"
	mappings loom.layered {
		officialMojangMappings {
			nameSyntheticMembers = true
		}
		parchment("org.parchmentmc.data:parchment-${project.parchment_mcversion}:${project.parchment_version}@zip")
	}
	modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
	modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
	productionRuntimeMods "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"

	include modImplementation("dev.xpple:clientarguments:${project.clientarguments_version}")
	include modImplementation("dev.xpple:betterconfig-fabric:${project.betterconfig_version}")
	include modImplementation("dev.xpple:simplewaypoints:${project.simplewaypoints_version}")

	includedLibrary "com.seedfinding:mc_feature:${project.seedfinding_feature_version}"
	includedLibrary "com.seedfinding:mc_biome:${project.seedfinding_biome_version}"
	includedLibrary "com.seedfinding:mc_core:${project.seedfinding_core_version}"
	includedLibrary "com.seedfinding:mc_seed:${project.seedfinding_seed_version}"

	includedLibrary "com.seedfinding:latticg:${project.latticg_version}:rt"
	codeGenImplementation "com.seedfinding:latticg:${project.latticg_version}"

	compileOnly 'com.demonwav.mcdev:annotations:2.0.0'

	modRuntimeOnly("me.djtheredstoner:DevAuth-fabric:${project.devauth_version}") {
		exclude group: 'net.fabricmc', module: 'fabric-loader'
	}
	productionRuntimeMods("me.djtheredstoner:DevAuth-fabric:${project.devauth_version}") {
		exclude group: 'net.fabricmc', module: 'fabric-loader'
	}

	include api("net.fabricmc:mapping-io:${project.mapping_io_version}")

	codeGenImplementation sourceSets.main.output

	testImplementation "net.fabricmc:fabric-loader-junit:${project.loader_version}"
	testImplementation "org.junit.jupiter:junit-jupiter:${project.junit_version}"
	testImplementation "com.code-intelligence:jazzer-junit:${project.jazzer_junit_version}"
}

checkstyle {
	toolVersion = project.checkstyle_version
	configFile = rootProject.file("checkstyle.xml")
	ignoreFailures = false
}

test {
	useJUnitPlatform()
	systemProperty('clientcommands.regressionTestDir', file('regressionTests').absolutePath)
}

jar {
	from(configurations.includedLibrary.collect { it.isDirectory() ? it : zipTree(it) }) {
		include 'com/seedfinding/**'
	}

	from("LICENSE")
}

tasks.register('generateBuildInfo', GenerateBuildInfoTask) {
	outputFile = new File(temporaryDir, "build_info.json")
}

processResources {
	inputs.property "version", project.version
	inputs.property "mcversion", project.minecraft_version_dependency

	duplicatesStrategy DuplicatesStrategy.WARN

	from(sourceSets.main.resources.srcDirs) {
		include "fabric.mod.json"
		expand "version": project.version, "mcversion": project.minecraft_version_dependency
	}

	from(sourceSets.main.resources.srcDirs) {
		exclude "fabric.mod.json"
	}

	from generateBuildInfo
}

java {
	sourceCompatibility = JavaVersion.VERSION_21
	targetCompatibility = JavaVersion.VERSION_21
}

tasks.withType(JavaCompile).configureEach {
	options.encoding = "UTF-8"
}

tasks.register("prodClient", ClientProductionRunTask) {
	runDir = file("run")

	jvmArgs.add("-Ddevauth.enabled=true")

	javaLauncher = javaToolchains.launcherFor {
		languageVersion = JavaLanguageVersion.of(21)
	}
}

tasks.register('sourcesJar', Jar) {
	dependsOn classes
	archiveClassifier.set("sources")
	from sourceSets.main.allSource
}

tasks.register('codeGen', JavaExec) {
	mainClass = 'net.earthcomputer.clientcommands.codegen.CodeGenerator'
	classpath = sourceSets.codeGen.runtimeClasspath
	args file('src/main/java').absolutePath
	enableAssertions = true
}

tasks.register('checkLanguageFiles', CheckLanguageFilesTask) {
	inputDir.set(file('src/main/resources/assets/clientcommands/lang'))
}
check.dependsOn checkLanguageFiles

// read the changelog from the changelog.txt file, make sure the changelog is recent to avoid accidentally using the previous version's changelog.
def changelogFile = file('changelog.txt')
def changelogText = changelogFile.exists() && System.currentTimeMillis() - changelogFile.lastModified() <= 1000 * 60 * 60 ?
		changelogFile.readLines('UTF-8').join('\n') : ''

modrinth {
	token = project.hasProperty('modrinthKey') ? project.modrinthKey : System.getenv("MODRINTH_TOKEN")
	projectId = 'client-commands'
	uploadFile = remapJar
	gameVersions.set(project.minecraft_version_list.split('\\s*,\\s*').toList())
	loaders.set(['fabric', 'quilt'])
	changelog = changelogText
	dependencies {
		required.project 'fabric-api'
		embedded.project 'betterconfig'
		embedded.project 'simplewaypoints'
	}
}
tasks.modrinth.onlyIf {
	!changelogText.isBlank()
}

githubRelease {
	token(project.hasProperty('githubKey') ? project.githubKey : (System.getenv("GITHUB_TOKEN") ?: ''))
	owner 'Earthcomputer'
	repo 'clientcommands'
	targetCommitish 'fabric'
	releaseName "Version ${project.version} for Minecraft ${project.minecraft_version_list_presentable}"
	body changelogText
	releaseAssets remapJar.outputs
}
tasks.githubRelease.onlyIf {
	!changelogText.isBlank()
}

publishing {
	publications {
		mavenJava(MavenPublication) {
			artifact(jar) {
				builtBy remapJar
			}
			artifact(sourcesJar) {
				builtBy remapSourcesJar
			}
		}
	}

	repositories {
		// mavenLocal()
	}
}
