/**
 * template-renderer.ts
 *
 * Simple {{var}} substitution for user templates. Intentionally minimal:
 *   - No conditionals, no loops, no helpers. If those become needed,
 *     graduate to Handlebars in a follow-up.
 *   - Unknown placeholders (var not declared in frontmatter.params) are
 *     left literal — so README-style templates with prose like "use {{x}}"
 *     don't blow up when there's no x param.
 *
 * Param semantics (type-check + defaults) are shared with scripts via
 * validateAndApplyDefaults from script-runner.ts; templates use the same
 * frontmatter.params schema as scripts/browser-macros.
 */

import type { ParamSpec } from './frontmatter.js';
import { validateAndApplyDefaults } from './script-runner.js';

/**
 * Replaces {{name}} with the corresponding param value, but only for params
 * that appear in `declared` (the validated set). Unknown {{xxx}} stays literal.
 */
export function renderTemplate(
  body: string,
  paramSpec: ParamSpec[],
  rawParams: Record<string, unknown>,
): string {
  const resolved = validateAndApplyDefaults(paramSpec, rawParams);
  return body.replace(/\{\{(\w+)\}\}/g, (match, name) =>
    Object.prototype.hasOwnProperty.call(resolved, name) ? String(resolved[name]) : match,
  );
}
