/**
 * Token Parser (Phase 1) – converts template text with {{category.field}} tokens
 * into a structure ready for rendering. Does NOT fetch live data; caller supplies
 * a resolver map of { category: { field: value } }.
 */

import { isValidToken } from './token-registry.js';

// CRITICAL: Use a fresh regex per call to avoid lastIndex issues with global flag
const TOKEN_PATTERN = '\\{\\{\\s*([a-z0-9_]+)\\.([a-z0-9_]+)\\s*\\}\\}';

export function extractTokens(templateText) {
  const found = new Set();
  if (typeof templateText !== 'string') return [];
  // Create fresh regex each call to avoid global lastIndex state issues
  const regex = new RegExp(TOKEN_PATTERN, 'ig');
  let m;
  while ((m = regex.exec(templateText)) !== null) {
    const cat = m[1];
    const field = m[2];
    const path = `${cat}.${field}`;
    if (isValidToken(path)) found.add(path);
  }
  return Array.from(found);
}

export function renderTemplate(templateText, dataMap) {
  if (typeof templateText !== 'string') return { rendered: '', tokens: [] };
  const tokens = extractTokens(templateText);
  let rendered = templateText;
  for (const t of tokens) {
    const [cat, field] = t.split('.');
    const value = dataMap?.[cat]?.[field];
    // Empty string if missing – per “no dummy fallback” rule (admin may show warning elsewhere)
    rendered = rendered.replaceAll(new RegExp(`\\{\\{\\s*${cat}\\.${field}\\s*\\}}`, 'gi'), value != null ? String(value) : '');
  }
  return { rendered, tokens };
}

// Debug helper
try { window.ccveTokenParser = { extractTokens, renderTemplate }; } catch(_) {}

export default { extractTokens, renderTemplate };
