import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { build } from "esbuild";

const project = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const out = resolve(project, "dist");
const resources = resolve(out, "resources");

await rm(out, { recursive: true, force: true });
await mkdir(resolve(out, "renderer"), { recursive: true });
await mkdir(resolve(resources, "assets"), { recursive: true });

await Promise.all([
  build({
    entryPoints: [resolve(project, "src/main.ts")],
    outfile: resolve(out, "main.cjs"),
    bundle: true,
    platform: "node",
    format: "cjs",
    target: "node22",
    external: ["electron"],
    alias: {
      "@xmcl/core/utils": resolve(project, "src/vendor/xmcl-core-utils.ts"),
    },
    sourcemap: true,
    legalComments: "external",
  }),
  build({
    entryPoints: [resolve(project, "src/preload.ts")],
    outfile: resolve(out, "preload.cjs"),
    bundle: true,
    platform: "node",
    format: "cjs",
    target: "node22",
    external: ["electron"],
    sourcemap: true,
    legalComments: "external",
  }),
  build({
    entryPoints: [resolve(project, "src/renderer/app.tsx")],
    outfile: resolve(out, "renderer/app.js"),
    bundle: true,
    platform: "browser",
    format: "iife",
    target: "chrome136",
    sourcemap: true,
    legalComments: "external",
  }),
  cp(resolve(project, "src/renderer/index.html"), resolve(out, "renderer/index.html")),
  cp(resolve(project, "src/renderer/design-tokens.css"), resolve(out, "renderer/design-tokens.css")),
  cp(resolve(project, "src/renderer/styles.css"), resolve(out, "renderer/styles.css")),
  cp(resolve(project, "src/assets/logo.png"), resolve(resources, "assets/logo.png")),
  cp(resolve(project, "src/assets/frame.png"), resolve(resources, "assets/frame.png")),
  cp(resolve(project, "../launcher-site/assets/hero-bglands-v2.webp"), resolve(resources, "assets/hero.webp")),
  cp(resolve(project, "../launcher-site/assets/bienvenue.webp"), resolve(resources, "assets/bienvenue.webp")),
  cp(resolve(project, "../launcher-site/assets/chakra-petch-400-latin.woff2"), resolve(resources, "assets/chakra-petch-400.woff2")),
  cp(resolve(project, "../launcher-site/assets/chakra-petch-500-latin.woff2"), resolve(resources, "assets/chakra-petch-500.woff2")),
  cp(resolve(project, "../launcher-site/assets/chakra-petch-600-latin.woff2"), resolve(resources, "assets/chakra-petch-600.woff2")),
  cp(resolve(project, "../launcher-site/assets/chakra-petch-700-latin.woff2"), resolve(resources, "assets/chakra-petch-700.woff2")),
]);

const template = JSON.parse(await readFile(resolve(project, "launcher.config.json"), "utf8"));
const clientId = process.env.BGLANDS_MICROSOFT_CLIENT_ID?.trim();
if (clientId) template.microsoft.clientId = clientId;
await writeFile(resolve(resources, "launcher.config.json"), `${JSON.stringify(template, null, 2)}\n`, { mode: 0o600 });
