import { getType } from "./content-schema-transform.js";
import { followRef, getRefShapeName } from "./refs.js";
import { getStorageKey, isBuiltinType } from "./schema-util.js";
import { isPropertySchemaWithRelationship } from "./types/index.js";
const scalarTags = new Set(['draftjs']);
function isLeafTypeV3(projectSchema, propertySchema) {
    const type = getType(propertySchema);
    return Boolean(
    // Must have key
    getStorageKey(propertySchema) &&
        // If is not a structure, then is a leaf
        (!['object', 'array'].includes(type) ||
            // If is relationship, then is a leaf
            isPropertySchemaWithRelationship(propertySchema['@output'] ?? propertySchema) ||
            Boolean(propertySchema['@tag'] && scalarTags.has(propertySchema['@tag'])) ||
            // If is array, then should not be a synchronized structure
            (type === 'array' && !propertySchema['@syncLocaleStructure']) ||
            isBuiltinType(projectSchema, propertySchema)));
}
export function getIsLeaf(projectSchema, shapeSchema) {
    const leafMap = new Set();
    const shapesSeen = new Set();
    const collectLeaves = (schema) => {
        const shapeName = getRefShapeName(projectSchema, schema);
        schema = shapeName ? followRef(projectSchema, schema) : schema;
        const key = getStorageKey(schema);
        if (key && isLeafTypeV3(projectSchema, schema)) {
            leafMap.add(key);
        }
        if (shapeName) {
            // Skip shapes we have already seen to avoid cycles
            if (shapesSeen.has(shapeName)) {
                return;
            }
            shapesSeen.add(shapeName);
        }
        const combo = schema.oneOf ?? schema.allOf;
        if (combo) {
            combo.map(collectLeaves);
        }
        else if (schema.properties) {
            for (const name of Object.keys(schema.properties)) {
                collectLeaves(schema.properties[name]);
            }
        }
        else if (schema.items) {
            collectLeaves(schema.items);
        }
    };
    collectLeaves(shapeSchema);
    return (key) => {
        // Remove locale suffix
        key = key ? key.split(':')[0] : key;
        return Boolean(key && leafMap.has(key));
    };
}
