import { createHash } from "node:crypto";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { pages, site } from "./content.mjs";

const websiteDir = dirname(fileURLToPath(import.meta.url));
const root = resolve(websiteDir, "..");
const outIndex = process.argv.indexOf("--out");
const output = resolve(outIndex >= 0 ? process.argv[outIndex + 1] : join(websiteDir, "dist"));
const styleAsset = await readFile(join(websiteDir, "assets", "site.css"));
const scriptAsset = await readFile(join(websiteDir, "assets", "site.js"));

function fingerprintedAssetName(name, extension, content) {
  const fingerprint = createHash("sha256").update(content).digest("hex").slice(0, 12);
  return `${name}.${fingerprint}.${extension}`;
}

const styleAssetName = fingerprintedAssetName("site", "css", styleAsset);
const scriptAssetName = fingerprintedAssetName("site", "js", scriptAsset);

function escapeHtml(value) {
  return value
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;");
}

function documentHtml(value) {
  return value
    .trim()
    .split(/\r?\n\r?\n/)
    .map((block) => {
      const escaped = escapeHtml(block.replaceAll(/\r?\n/g, " "));
      return `<p>${escaped.replaceAll(/(https:\/\/[^\s<]+)/g, '<a href="$1">$1</a>')}</p>`;
    })
    .join("\n");
}

function nav(route) {
  const items = [
    ["", "홈", "Home"],
    ["download", "다운로드", "Download"],
    ["privacy", "개인정보", "Privacy"],
    ["terms", "약관", "Terms"],
    ["support", "지원", "Support"],
    ["delete-account", "삭제", "Deletion"],
    ["licenses", "라이선스", "Licenses"],
  ];
  return items.map(([path, ko, en]) => {
    const href = path ? `/${path}` : "/";
    const active = path === route ? ' aria-current="page"' : "";
    return `<a href="${href}"${active}><span data-lang-label="ko">${ko}</span><span data-lang-label="en">${en}</span></a>`;
  }).join("");
}

async function renderPage(page) {
  let english = page.en ?? "";
  if (page.englishDocument) english = documentHtml(await readFile(join(root, page.englishDocument), "utf8"));
  if (page.noticesDocuments) {
    const notices = escapeHtml((await Promise.all(
      page.noticesDocuments.map((path) => readFile(join(root, path), "utf8")),
    )).join(`\n\n${"=".repeat(72)}\n\n`));
    english = `<p class="eyebrow">Licenses</p><h1>Third-Party Notices</h1><p class="lede">Notices generated from the verified release dependency inventory.</p><pre class="notices">${notices}</pre>`;
  }
  const updatedKo = page.updated
    ? `<p class="document-updated"><span>최종 수정일</span> <time datetime="${page.updated}">${page.updated}</time></p>`
    : "";
  const updatedEn = page.updated
    ? `<p class="document-updated"><span>Last updated</span> <time datetime="${page.updated}">${page.updated}</time></p>`
    : "";
  const canonical = `${site.origin}${page.route ? `/${page.route}` : "/"}`;
  return `<!doctype html>
<html lang="ko" data-lang="ko">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="${escapeHtml(page.description)}">
  <meta name="theme-color" content="#11100e">
  <link rel="canonical" href="${canonical}">
  <link rel="stylesheet" href="/assets/${styleAssetName}">
  <script src="/assets/${scriptAssetName}" defer></script>
  <title>${page.route ? `${escapeHtml(page.titleKo)} | Code Remote Manager` : "Code Remote Manager"}</title>
</head>
<body>
  <header class="site-header">
    <a class="brand" href="/" aria-label="Code Remote Manager 홈">Code Remote Manager</a>
    <div class="language" role="group" aria-label="언어 선택">
      <button type="button" data-set-lang="ko" aria-pressed="true">한국어</button>
      <button type="button" data-set-lang="en" aria-pressed="false">English</button>
    </div>
    <nav aria-label="공개 정보">${nav(page.route)}</nav>
  </header>
  <main>
    <article data-lang-content="ko">${updatedKo}${page.ko}</article>
    <article data-lang-content="en">${updatedEn}${english}</article>
  </main>
  <footer>
    <small class="copyright">© 2026 Code Remote Manager</small>
    <a href="mailto:${site.email}">${site.email}</a>
  </footer>
</body>
</html>`;
}

await rm(output, { recursive: true, force: true });
await mkdir(join(output, "assets"), { recursive: true });
await Promise.all([
  writeFile(join(output, "assets", styleAssetName), styleAsset),
  writeFile(join(output, "assets", scriptAssetName), scriptAsset),
]);
for (const page of pages) {
  const directory = join(output, page.route);
  await mkdir(directory, { recursive: true });
  await writeFile(join(directory, "index.html"), await renderPage(page));
}
await writeFile(join(output, "404.html"), await renderPage(pages[0]));
console.log(`Built ${pages.length} public routes in ${output}`);
