/**
 * Legacy visible-state projection upgrade helper.
 *
 * This file intentionally lives under scripts/migrations. Runtime source
 * does not support retired state/checkpoint schemas; it only exposes the
 * current substrate.
 */
import { createEmptyState } from "../../../src/domain/services/JoinReducer.js";
import VersionVector from "../../../src/domain/crdt/VersionVector.js";
export function upgradeVisibleStateProjection(legacyState, migrationWriterId) {
    const currentState = createEmptyState();
    const vv = VersionVector.empty();
    upgradeAliveEntities({ legacyState, currentState, vv, migrationWriterId });
    upgradeVisibleProps(legacyState, currentState);
    currentState.observedFrontier = vv;
    return currentState;
}
function upgradeAliveEntities({ legacyState, currentState, vv, migrationWriterId, }) {
    for (const [nodeId, reg] of legacyState.nodeAlive) {
        if (reg.value) {
            const dot = vv.increment(migrationWriterId);
            currentState.nodeAlive.add(nodeId, dot);
        }
    }
    for (const [edgeKey, reg] of legacyState.edgeAlive) {
        if (reg.value) {
            const dot = vv.increment(migrationWriterId);
            currentState.edgeAlive.add(edgeKey, dot);
        }
    }
}
function upgradeVisibleProps(legacyState, currentState) {
    for (const [propKey, reg] of legacyState.prop) {
        const idx = propKey.indexOf('\0');
        const nodeId = propKey.slice(0, idx);
        const nodeReg = legacyState.nodeAlive.get(nodeId);
        if (nodeReg?.value === true) {
            currentState.mutatePropLWW(propKey, reg.eventId, reg.value);
        }
    }
}
