import { mkdtemp, mkdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { ClientReleaseManager } from "../src/main/release.ts";
import type { LauncherConfig, LauncherPaths } from "../src/main/config.ts";
import { LauncherLogger } from "../src/main/logger.ts";

const root = await mkdtemp(join(tmpdir(), "bglands-launcher-release-smoke-"));
const paths: LauncherPaths = {
  root,
  instance: join(root, "instance"),
  minecraft: join(root, "minecraft"),
  runtime: join(root, "runtime"),
  cache: join(root, "cache"),
  logs: join(root, "logs"),
  state: join(root, "state.json"),
  settings: join(root, "settings.json"),
  microsoftConfig: join(root, "microsoft.json"),
  msalCache: join(root, "auth.cache"),
  config: resolve("launcher.config.json"),
};
const config: LauncherConfig = {
  schemaVersion: 1,
  launcherVersion: "1.0.1",
  releaseManifestUrl: "https://game.bglands.fr/resources/bglands-client/release.json",
  releaseHost: "game.bglands.fr",
  server: { host: "game.bglands.fr", port: 25565 },
  microsoft: {
    clientId: "",
    authority: "https://login.microsoftonline.com/consumers",
    scopes: ["XboxLive.signin", "XboxLive.offline_access"],
    source: "missing",
  },
  defaults: {
    minimumMemoryMb: 2_048,
    maximumMemoryMb: 6_144,
    width: 1_280,
    height: 720,
    autoConnect: true,
    closeLauncherOnGameStart: false,
  },
};

try {
  await Promise.all([mkdir(paths.instance, { recursive: true }), mkdir(paths.cache, { recursive: true })]);
  const logger = new LauncherLogger(paths.logs);
  await logger.initialize();
  const manifest = await new ClientReleaseManager(config, paths, logger).synchronize((progress) => {
    process.stdout.write(`${progress.stage}: ${progress.message}\n`);
  });
  process.stdout.write(`OK ${manifest.payload.releaseId} ${manifest.integrity.payloadSha256}\n`);
} finally {
  await rm(root, { recursive: true, force: true });
}
