import { deepClone } from '@takeshape/util';
import set from 'lodash/set.js';
import { refItemToNamespacedShapeName } from "./refs.js";
import { getAllRefs } from "./schema-util.js";
import { isValidTemplate, resolveTemplate } from "./template-shapes/index.js";
export function flattenTemplates(projectSchema) {
    const templateRefs = getAllRefs(projectSchema, (ref) => Boolean(ref.template));
    if (!templateRefs.length) {
        return projectSchema;
    }
    const newSchema = deepClone(projectSchema);
    for (const ref of templateRefs) {
        if (ref.template && isValidTemplate(ref.template)) {
            const { shapeName, dependencies } = resolveTemplate(newSchema, ref.template, refItemToNamespacedShapeName(newSchema, ref));
            set(newSchema, ref.path, ref.path[ref.path.length - 1] === '@ref' ? `local:${shapeName}` : shapeName);
            Object.assign(newSchema.shapes, dependencies);
        }
    }
    return newSchema;
}
