#!/usr/bin/env node
/**
 * DocFast HTML Build Script
 * Replaces {{> partial_name}} in source files with partial contents.
 * Source: public/src/*.html → Output: public/*.html
 * Partials: public/partials/_*.html
 */
const fs = require('fs');
const path = require('path');

const srcDir = path.join(__dirname, '..', 'public', 'src');
const outDir = path.join(__dirname, '..', 'public');
const partialsDir = path.join(__dirname, '..', 'public', 'partials');

// Load all partials
const partials = {};
if (fs.existsSync(partialsDir)) {
  for (const f of fs.readdirSync(partialsDir)) {
    if (f.startsWith('_') && f.endsWith('.html')) {
      const name = f.replace(/^_/, '').replace(/\.html$/, '');
      partials[name] = fs.readFileSync(path.join(partialsDir, f), 'utf-8').trimEnd();
    }
  }
}
console.log(`Loaded partials: ${Object.keys(partials).join(', ')}`);

if (!fs.existsSync(srcDir)) {
  console.error(`Source directory not found: ${srcDir}`);
  process.exit(1);
}

// Process each source file
const files = fs.readdirSync(srcDir).filter(f => f.endsWith('.html'));
for (const file of files) {
  let content = fs.readFileSync(path.join(srcDir, file), 'utf-8');
  
  // Replace {{> partial_name}} with partial content
  content = content.replace(/\{\{>\s*(\w+)\s*\}\}/g, (match, name) => {
    if (partials[name]) return partials[name];
    console.warn(`  Warning: partial '${name}' not found in ${file}`);
    return match;
  });
  
  const outPath = path.join(outDir, file);
  fs.writeFileSync(outPath, content);
  console.log(`  Built: ${file}`);
}
console.log('Done.');
