import { mkdir, rm, writeFile, copyFile, readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";

const siteRoot = new URL("./", import.meta.url);
const outputRoot = new URL("../_site/", import.meta.url);

const cssFiles = ["styles/tokens.css", "styles/base.css", "styles/components.css", "styles/sections.css"];
const jsFiles = ["scripts/i18n.js", "scripts/theme.js", "scripts/main.js"];
// Icons are the site's own brand-colored copies under site/assets/icons/ (the app's
// assets/icons/ stay mask-only currentColor and must not be mutated to serve the web).
// tray-claude / tray-codex are the real tray glyphs, masked to monochrome in the surfaces section.
const iconNames = ["claude", "codex", "cursor", "antigravity", "hermes-agent", "opencode", "openclaw", "os-apple", "os-windows", "tray-claude", "tray-codex", "gemini", "xai", "deepseek", "qwen", "moonshot", "mistral", "meta", "zai", "minimax", "cline"];
const assets = [
  ["assets/app.png", "assets/app.png"], // full app icon used by the Discord mockup
  ["assets/icon.png", "assets/icon.png"], // nav brand mark (glass sigma)
  ...iconNames.map((name) => [`assets/icons/${name}.svg`, `assets/icons/${name}.svg`]),
];

async function concat(files) {
  const parts = [];
  for (const f of files) parts.push(await readFile(new URL(f, siteRoot), "utf8"));
  return parts.join("\n");
}
function rewriteHtml(html) {
  // collapse the 4 dev CSS links into one, and the 3 dev scripts into one
  return html
    .replace(/\s*<link rel="stylesheet" href="styles\/tokens\.css(?:\?[^"]*)?">[\s\S]*?<link rel="stylesheet" href="styles\/sections\.css(?:\?[^"]*)?">/, '\n    <link rel="stylesheet" href="styles.css">')
    .replace(/\s*<script src="scripts\/i18n\.js(?:\?[^"]*)?" defer><\/script>[\s\S]*?<script src="scripts\/main\.js" defer><\/script>/, '\n    <script src="app.js" defer></script>')
    .replace(/url\(\.\.\/assets\//g, "url(assets/");
}

await rm(outputRoot, { recursive: true, force: true });
await mkdir(new URL("assets/", outputRoot), { recursive: true }); // also creates _site/ root
await mkdir(new URL("assets/icons/", outputRoot), { recursive: true });

await writeFile(new URL("styles.css", outputRoot), await concat(cssFiles));
await writeFile(new URL("app.js", outputRoot), await concat(jsFiles));

const html = await readFile(new URL("index.html", siteRoot), "utf8");
await writeFile(new URL("index.html", outputRoot), rewriteHtml(html));

for (const [src, dest] of assets) await copyFile(new URL(src, siteRoot), new URL(dest, outputRoot));

console.log(`Built GitHub Pages site at ${fileURLToPath(outputRoot)}`);
