import { createHash } from "node:crypto";

const minecraft = "26.2";
const fabric = "0.19.3";
const versionIndexResponse = await fetch("https://piston-meta.mojang.com/mc/game/version_manifest_v2.json");
if (!versionIndexResponse.ok) throw new Error(`Index Mojang HTTP ${versionIndexResponse.status}`);
const versionIndex = await versionIndexResponse.json() as {
  versions: Array<{ id: string; url: string; sha1: string }>;
};
const entry = versionIndex.versions.find((candidate) => candidate.id === minecraft);
if (!entry) throw new Error(`Minecraft ${minecraft} absent de l'index Mojang`);
const versionResponse = await fetch(entry.url);
if (!versionResponse.ok) throw new Error(`Version Mojang HTTP ${versionResponse.status}`);
const versionBytes = new Uint8Array(await versionResponse.arrayBuffer());
const versionSha1 = createHash("sha1").update(versionBytes).digest("hex");
if (versionSha1 !== entry.sha1) throw new Error("SHA-1 du JSON de version Mojang invalide");
const version = JSON.parse(new TextDecoder().decode(versionBytes)) as {
  javaVersion: { component: string; majorVersion: number };
};
if (version.javaVersion.majorVersion < 25) throw new Error("La version n'annonce pas Java 25+");

const runtimeResponse = await fetch(
  "https://piston-meta.mojang.com/v1/products/java-runtime/2ec0cc96c44e5a76b9c8b7c39df7210883d12871/all.json",
);
if (!runtimeResponse.ok) throw new Error(`Index runtime Mojang HTTP ${runtimeResponse.status}`);
const runtimes = await runtimeResponse.json() as Record<string, Record<string, unknown[]>>;
if (!runtimes["windows-x64"]?.[version.javaVersion.component]?.length) {
  throw new Error(`Runtime ${version.javaVersion.component} absent pour Windows x64`);
}
const fabricResponse = await fetch(`https://meta.fabricmc.net/v2/versions/loader/${minecraft}/${fabric}`);
if (!fabricResponse.ok) throw new Error(`Métadonnées Fabric HTTP ${fabricResponse.status}`);
const fabricArtifact = await fabricResponse.json() as { loader?: { version?: string } };
if (fabricArtifact.loader?.version !== fabric) throw new Error("Version Fabric inattendue");

process.stdout.write(
  `OK Minecraft ${minecraft}, Java ${version.javaVersion.majorVersion} (${version.javaVersion.component}), Fabric ${fabricArtifact.loader.version}\n`,
);
