import set from 'lodash/fp/set.js';
import get from 'lodash/get.js';
import omit from 'lodash/omit.js';
import unset from 'lodash/unset.js';
import { AGENTS_UPDATE_KEY, GUARDS_UPDATE_KEY, MCP_TOOLS_UPDATE_KEY } from "../migration/types.js";
/**
 * Array of lodash.get paths to keys that are merged when applying a schema update.
 */
const schemaUpdateMergedKeys = [
    'queries',
    'mutations',
    'shapes',
    'workflows',
    'forms',
    'services',
    AGENTS_UPDATE_KEY,
    GUARDS_UPDATE_KEY,
    MCP_TOOLS_UPDATE_KEY
];
function shallowMerge(original, update) {
    const result = { ...original };
    for (const [key, obj] of Object.entries(update)) {
        // Null is a sentinel value to indicate delete
        if (obj === null) {
            unset(result, key);
        }
        else {
            result[key] = obj;
        }
    }
    return result;
}
/**
 * Apply a schema update to a schema. This can operate on a schema with frozen properties,
 * such as one produced by immer. Resulting schema is not assumed to be valid and should
 * be validated if appropriate.
 */
export function patchSchema(projectSchema, schemaUpdate) {
    // Patch old schema with update
    let updatedSchema = {
        ...projectSchema,
        ...omit(schemaUpdate, schemaUpdateMergedKeys)
    };
    for (const key of schemaUpdateMergedKeys) {
        const update = get(schemaUpdate, key);
        if (update) {
            updatedSchema = set(key, shallowMerge(get(projectSchema, key) ?? {}, update), updatedSchema);
        }
    }
    return updatedSchema;
}
