import { resolve } from "node:path";
import { assertKnownArgs, parseArgs, reportCliError, requiredArg } from "./cli.ts";
import { installRelease, readManifest } from "./installer.ts";

async function main(): Promise<void> {
  const args = parseArgs(process.argv.slice(2));
  assertKnownArgs(args, [
    "manifest", "public-key", "artifact-cache", "instance", "launcher-version",
    "minecraft", "java-major", "loader", "loader-version", "server-protocol",
  ]);
  const loader = requiredArg(args, "loader");
  if (loader !== "fabric" && loader !== "neoforge") throw new Error("--loader doit valoir fabric ou neoforge");
  const javaMajor = Number(requiredArg(args, "java-major"));
  const serverProtocol = Number(requiredArg(args, "server-protocol"));
  const result = await installRelease({
    manifest: await readManifest(resolve(requiredArg(args, "manifest"))),
    publicKeyPath: resolve(requiredArg(args, "public-key")),
    artifactCache: resolve(requiredArg(args, "artifact-cache")),
    instanceRoot: resolve(requiredArg(args, "instance")),
    environment: {
      launcherVersion: requiredArg(args, "launcher-version"),
      minecraft: requiredArg(args, "minecraft"),
      javaMajor,
      loader,
      loaderVersion: requiredArg(args, "loader-version"),
      serverProtocol,
    },
  });
  process.stdout.write(result.changed
    ? `Release ${result.manifest.payload.releaseId} installée (${result.installed.join(", ")})${
        result.removed.length === 0 ? "" : `; anciens artefacts sauvegardés (${result.removed.join(", ")})`
      }.\n`
    : `Release ${result.manifest.payload.releaseId} déjà valide; aucune modification.\n`);
}

main().catch(reportCliError);
