import * as fs from 'fs';
import * as path from 'path';
import Twig from 'twig';

export class TemplateEngine {
  private templatesDir: string;

  constructor() {
    this.templatesDir = path.join(process.cwd(), 'templates');
    
    // Configure Twig settings
    Twig.cache(false); // Disable caching for development
  }

  async render(templateName: string, data: any = {}): Promise<string> {
    try {
      const templatePath = path.join(this.templatesDir, templateName);
      console.log(`Rendering template: ${templateName} at ${templatePath}`);
      
      const templateContent = fs.readFileSync(templatePath, 'utf-8');
      console.log(`Template content length: ${templateContent.length}`);
      console.log('Data keys:', Object.keys(data));
      
      // Use the real Twig engine to render the template
      const template = Twig.twig({
        data: templateContent,
        path: templatePath,
        base: this.templatesDir
      });
      
      return template.render(data);
    } catch (error) {
      console.error('Template rendering error:', error);
      console.error('Error compiling twig template', templateName, ':', error);
      return `<div class="alert alert-danger">Template Error: ${(error as Error).message}</div>`;
    }
  }
}

export const templateEngine = new TemplateEngine();