/**
 * Simple template engine for HTML generation
 * Handles template loading and placeholder replacement
 */
import * as fs from 'fs';
import * as path from 'path';
export class TemplateEngine {
    templateCache = new Map();
    templatesDir;
    constructor() {
        const __dirname = path.dirname(new URL(import.meta.url).pathname);
        this.templatesDir = path.join(__dirname, 'templates');
    }
    /**
     * Load a template file with caching
     */
    loadTemplate(templateName) {
        if (this.templateCache.has(templateName)) {
            return this.templateCache.get(templateName);
        }
        const templatePath = path.join(this.templatesDir, templateName);
        try {
            const content = fs.readFileSync(templatePath, 'utf-8');
            this.templateCache.set(templateName, content);
            return content;
        }
        catch (error) {
            throw new Error(`Failed to load template ${templateName}: ${error}`);
        }
    }
    /**
     * Replace placeholders in template with variables
     */
    replacePlaceholders(template, variables) {
        let result = template;
        for (const [key, value] of Object.entries(variables)) {
            const placeholder = `{{${key}}}`;
            result = result.replace(new RegExp(placeholder, 'g'), value || '');
        }
        return result;
    }
    /**
     * Render a complete page using base template + content template
     */
    renderPage(contentTemplate, variables) {
        const baseTemplate = this.loadTemplate('base-template.html');
        const contentHtml = this.loadTemplate(contentTemplate);
        // First render the content template
        const renderedContent = this.replacePlaceholders(contentHtml, variables);
        // Then render the base template with the content
        const pageVariables = {
            ...variables,
            CONTENT: renderedContent
        };
        return this.replacePlaceholders(baseTemplate, pageVariables);
    }
    /**
     * Render just a template fragment
     */
    renderTemplate(templateName, variables) {
        const template = this.loadTemplate(templateName);
        return this.replacePlaceholders(template, variables);
    }
}
//# sourceMappingURL=template-engine.js.map