// Copyright (c) 2026 Modelware. All rights reserved.

import type { TemplateDefinition } from './types.js';

export interface TemplateCatalog {
    readonly byId: ReadonlyMap<string, TemplateDefinition>;
    readonly all: ReadonlyArray<TemplateDefinition>;
}

export function buildTemplateCatalog(templates: ReadonlyArray<TemplateDefinition>): TemplateCatalog {
    const byId = new Map<string, TemplateDefinition>();
    for (const template of templates) {
        const id = normalizeTemplateId(template.id);
        if (!id) {
            continue;
        }
        byId.set(id, { ...template, id });
    }
    return {
        byId,
        all: [...byId.values()]
    };
}

export function normalizeTemplateId(value: string): string {
    return value.trim().replace(/^<|>$/g, '');
}

export function getTemplateById(catalog: TemplateCatalog, templateId: string): TemplateDefinition | undefined {
    const normalized = normalizeTemplateId(templateId);
    if (!normalized) {
        return undefined;
    }
    return catalog.byId.get(normalized);
}
