import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';

const dashboardRoot = resolve(import.meta.dirname, '..');
const clientRoot = resolve(dashboardRoot, 'dist');
const serverRoot = resolve(dashboardRoot, '.prerender-build');
const template = await readFile(resolve(clientRoot, 'index.html'), 'utf8');
const { renderRoute, staticRoutes } = await import(pathToFileURL(resolve(serverRoot, 'prerender.js')));

// Keep the empty application shell for private and database-backed routes. The
// server inserts useful public project/profile HTML into this shell on request.
await writeFile(resolve(clientRoot, 'shell.html'), template);

for (const route of staticRoutes) {
  // Some text extractors discard extremely long source lines. React's static
  // renderer emits one line, so give every element a normal line boundary.
  const rendered = renderRoute(route).replace(/></g, '>\n<');
  const canonical = `https://omalled.com/polyform${route === '/' ? '/' : route}`;
  const html = template
    .replace('https://omalled.com/polyform/" />', `${canonical}" />`)
    .replace('<div id="root"></div>', `<div id="root">${rendered}</div>`);
  const output = route === '/'
    ? resolve(clientRoot, 'index.html')
    : resolve(clientRoot, 'prerender', route.slice(1), 'index.html');
  await mkdir(dirname(output), { recursive: true });
  await writeFile(output, html);
}

await rm(serverRoot, { recursive: true, force: true });
