import { mkdir, rm, readFile, writeFile, copyFile, cp } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import data from '../src/portfolio.mjs';

const started = performance.now();
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const output = resolve(root, 'dist');
const esc = value => String(value).replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]));
const { identity: p, ui } = data;

if (data.sections.length !== 3 || data.projects.length !== 3) throw new Error('This instrument expects three sections and three projects.');
for (const project of data.projects) {
  for (const key of ['id', 'title', 'description', 'detail', 'role', 'format', 'annotation']) {
    if (typeof project[key] !== 'string' || !project[key].trim()) throw new Error(`Missing ${key} in a project.`);
  }
  if (!['marine', 'type', 'mechanical'].includes(project.type)) throw new Error('Unknown project diagram type.');
}

await mkdir(output, { recursive: true });
await cp(resolve(root, 'public'), output, { recursive: true });
for (const name of ['app.mjs', 'styles.css', 'portfolio.mjs']) await copyFile(resolve(root, 'src', name), resolve(output, name));
let html = await readFile(resolve(root, 'src/index.html'), 'utf8');
html = html.replaceAll('@@TITLE@@', esc(`${p.title} — ${p.name}`))
  .replaceAll('@@DESCRIPTION@@', esc(`${p.name}, ${p.role.toLowerCase()}. ${p.fictionalNote}`))
  .replaceAll('@@PLAIN@@', esc(ui.plainView));
await writeFile(resolve(output, 'index.html'), html);

// The plain view is real, static HTML: complete portfolio content with JavaScript disabled.
const plain = `<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(ui.plainHeading)} — ${esc(p.name)}</title><meta name="description" content="${esc(p.fictionalNote)}"><link rel="icon" href="./favicon.svg" type="image/svg+xml"><style>
:root{font:100%/1.7 system-ui,sans-serif;color:#172b27;background:#fcfcf8}*{box-sizing:border-box}body{max-width:760px;margin:auto;padding:32px 24px 60px}a{color:#245d47;text-underline-offset:4px}a:focus-visible{outline:3px solid #a35426;outline-offset:5px}header{border-bottom:1px solid #bbc6b9;padding-bottom:24px}h1,h2,h3{line-height:1.2}h1{font-size:2.2rem;letter-spacing:-.04em}h2{font-size:1.65rem;margin-top:40px}h3{font-size:1.3rem}p{margin:12px 0}nav{display:flex;gap:24px;flex-wrap:wrap;padding-top:16px}nav a{padding:8px 0}article{padding:8px 0 24px;border-bottom:1px solid #c9d1c3}.meta{font-size:.9rem;color:#40594c}dt{font-weight:650}dd{margin-left:0;margin-bottom:10px}.address{font-size:1.25rem;overflow-wrap:anywhere}footer{margin-top:48px;border-top:1px solid #bbc6b9;padding-top:20px;font-size:.9rem}section{scroll-margin-top:20px}
</style></head><body>
<header><a href="./">← ${esc(ui.returnView)}</a><h1>${esc(p.name)}</h1><p>${esc(p.role)} · ${esc(p.title)}</p><p>${esc(p.headline.join(' '))}</p><p>${esc(p.introduction)}</p><p class="meta">${esc(p.fictionalNote)}</p><nav aria-label="${esc(ui.plainHeading)}">${data.sections.map(s => `<a href="#${esc(s.id)}">${esc(s.label)}</a>`).join('')}</nav></header>
<main><section id="work"><h2>${esc(data.sections[0].label)} — ${esc(ui.workHeading)}</h2>${data.projects.map(project => `<article><h3>${esc(project.title)}</h3><p class="meta">${esc(ui.demoLabel)} · ${esc(project.year)} · ${esc(project.category)}</p><p>${esc(project.description)}</p><p>${esc(project.detail)}</p><p><em>${esc(project.annotation)}</em> ${esc(ui.artNote)}.</p><dl><dt>${esc(ui.role)}</dt><dd>${esc(project.role)}</dd><dt>${esc(ui.format)}</dt><dd>${esc(project.format)}</dd></dl></article>`).join('')}</section>
<section id="about"><h2>${esc(data.sections[1].label)} — ${esc(ui.aboutHeading)}</h2>${data.about.paragraphs.map(text => `<p>${esc(text)}</p>`).join('')}<dl>${data.about.principles.map(item => `<dt>${esc(item.title)}</dt><dd>${esc(item.text)}</dd>`).join('')}</dl></section>
<section id="contact"><h2>${esc(data.sections[2].label)} — ${esc(ui.contactHeading)}</h2><p>${esc(data.contact.paragraph)}</p><p class="meta">${esc(ui.contactLabel)}</p><p class="address">${esc(p.contact)}</p><p>${esc(ui.contactNote)}</p></section></main>
<footer>${esc(p.footer)}<br>${esc(p.copyright)}</footer></body></html>`;
await writeFile(resolve(output, 'text.html'), plain);
console.log(`Built local static site in dist/ (${((performance.now() - started) / 1000).toFixed(3)} seconds).`);
