/**
 * Simple template engine for scaffolding.
 * Supports {{VARIABLE}} replacement and {{#IF FEATURE}}...{{/IF FEATURE}} conditional blocks.
 */

export type TemplateVars = Record<string, string | boolean | number>;

/**
 * Replace {{VARIABLE}} placeholders and process {{#IF FEATURE}}...{{/IF FEATURE}} blocks.
 */
export function renderTemplate(template: string, vars: TemplateVars): string {
  let result = template;

  // Process conditional blocks: {{#IF KEY}}...{{/IF KEY}}
  const ifRegex = /\{\{#IF (\w+)\}\}([\s\S]*?)\{\{\/IF \1\}\}/g;
  result = result.replace(ifRegex, (_, key: string, content: string) => {
    return vars[key] ? content : '';
  });

  // Process negative conditional blocks: {{#UNLESS KEY}}...{{/UNLESS KEY}}
  const unlessRegex = /\{\{#UNLESS (\w+)\}\}([\s\S]*?)\{\{\/UNLESS \1\}\}/g;
  result = result.replace(unlessRegex, (_, key: string, content: string) => {
    return !vars[key] ? content : '';
  });

  // Replace {{VARIABLE}} placeholders
  result = result.replace(/\{\{(\w+)\}\}/g, (match, key: string) => {
    const val = vars[key];
    if (val === undefined) return match;
    return String(val);
  });

  return result;
}
