/**
 * Replaces variables in a template string with provided values.
 * Handles standard variables like {{ownerName}}, {{propertyAddress}}, {{date}}.
 * 
 * @param {string} content - The template content (HTML or text)
 * @param {Object} variables - Dictionary of variable values
 * @param {Object} contextData - Context object (e.g. client/owner info) for fallback or auto-fill
 * @returns {string} - The content with variables replaced
 */
export const replaceTemplateVariables = (content, variables = {}, contextData = {}) => {
  if (!content) return '';

  let processedContent = content;

  // 1. Merge explicitly provided variables with context defaults if not present
  const finalVariables = { ...variables };

  // Auto-fill common context if available and not overridden
  if (contextData.ownerName && !finalVariables.ownerName) finalVariables.ownerName = contextData.ownerName;
  if (contextData.propertyAddress && !finalVariables.propertyAddress) finalVariables.propertyAddress = contextData.propertyAddress;
  if (contextData.clientName && !finalVariables.clientName) finalVariables.clientName = contextData.clientName;
  
  // Always provide date if not set
  if (!finalVariables.date) {
    finalVariables.date = new Date().toLocaleDateString();
  }

  // 2. Perform replacement
  Object.keys(finalVariables).forEach(key => {
    // Escape special regex chars in key just in case, though keys are usually simple
    const regex = new RegExp(`{{${key}}}`, 'g');
    const value = finalVariables[key] !== undefined && finalVariables[key] !== null ? finalVariables[key] : '';
    processedContent = processedContent.replace(regex, value);
  });

  // 3. Clean up any remaining unreplaced variables (optional: replace with empty string or keep)
  // For now, we'll leave them or replace specific known ones with fallbacks
  
  return processedContent;
};

/**
 * Extracts unique variable names from content
 */
export const extractVariables = (content) => {
  if (!content) return [];
  const matches = content.match(/{{([^}]+)}}/g) || [];
  return [...new Set(matches.map(m => m.replace(/{{|}}/g, '')))];
};