// Template Engine Service
// Processes agreement templates with variable substitution

export class TemplateEngine {
  /**
   * Process template with variables
   */
  async process(template: string, variables: Record<string, any>): Promise<string> {
    let processed = template;

    // Replace variables in format {{variableName}}
    for (const [key, value] of Object.entries(variables)) {
      const regex = new RegExp(`\\{\\{${key}\\}\\}`, 'g');
      processed = processed.replace(regex, this.formatValue(value));
    }

    // Replace nested variables (e.g., {{object.property}})
    processed = this.processNestedVariables(processed, variables);

    return processed;
  }

  /**
   * Format value for template
   */
  private formatValue(value: any): string {
    if (value === null || value === undefined) {
      return '';
    }

    if (typeof value === 'object') {
      return JSON.stringify(value, null, 2);
    }

    return String(value);
  }

  /**
   * Process nested variables
   */
  private processNestedVariables(template: string, variables: Record<string, any>): string {
    // Match patterns like {{object.property}}
    const nestedRegex = /\{\{([a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z0-9_.]+)\}\}/g;
    
    return template.replace(nestedRegex, (match, path) => {
      const value = this.getNestedValue(variables, path);
      return this.formatValue(value);
    });
  }

  /**
   * Get nested value from object
   */
  private getNestedValue(obj: any, path: string): any {
    return path.split('.').reduce((current, key) => {
      return current && current[key] !== undefined ? current[key] : null;
    }, obj);
  }
}

export const templateEngine = new TemplateEngine();
