// tools/event-contracts/schema-helpers.ts — Schema evolution and Saga diagram helpers
export function evolveSchema(current, addedFields, removedFields, changedFields, deprecatedFields) {
    const allProps = asPropertiesMap(current.properties);
    const fieldsToRemove = new Set(removedFields ?? []);
    const props = Object.fromEntries(Object.entries(allProps).filter(([k]) => !fieldsToRemove.has(k)));
    const required = asStringArray(current.required).filter((f) => !fieldsToRemove.has(f));
    for (const change of changedFields ?? []) {
        if (props[change.field]) {
            props[change.field] = { ...props[change.field], type: change.to };
        }
    }
    for (const dep of deprecatedFields ?? []) {
        if (props[dep.field]) {
            props[dep.field] = {
                ...props[dep.field],
                deprecated: true,
                sunsetVersion: dep.sunsetVersion,
            };
        }
    }
    for (const field of addedFields ?? []) {
        props[field] = { type: 'string', description: `New field: ${field}` };
        // Not added to required — new fields are optional by convention
    }
    return { ...current, properties: props, required };
}
export function buildSagaMermaid(saga) {
    const lines = [
        `stateDiagram-v2`,
        `  title: ${saga.id}`,
        `  [*] --> ${saga.steps[0]?.id ?? 'start'}`,
    ];
    for (const step of saga.steps) {
        lines.push(`  ${step.id} --> ${step.id}_done : ${step.successEvent}`);
        lines.push(`  ${step.id} --> ${step.id}_compensate : ${step.failureEvent}`);
        lines.push(`  ${step.id}_compensate --> [*] : ${step.compensationEvent}`);
    }
    // Chain the happy path (noUncheckedIndexedAccess requires explicit guards)
    /* v8 ignore start */
    for (let i = 0; i < saga.steps.length - 1; i++) {
        const current = saga.steps[i];
        const next = saga.steps[i + 1];
        if (current && next) {
            lines.push(`  ${current.id}_done --> ${next.id}`);
        }
    }
    /* v8 ignore stop */
    const last = saga.steps.at(-1);
    if (last) {
        lines.push(`  ${last.id}_done --> [*]`);
    }
    return lines.join('\n');
}
export function asStringArray(value) {
    return Array.isArray(value) ? value : [];
}
export function asPropertiesMap(value) {
    if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
        return value;
    }
    return {};
}
export function errorResult(message) {
    return {
        content: [{ type: 'text', text: message }],
        isError: true,
    };
}
//# sourceMappingURL=schema-helpers.js.map