/**
 * RuntimePatchCollector — adapter wrapping WarpRuntime's patch loading internals.
 *
 * Lives at the infrastructure boundary. Domain code (MaterializeController)
 * programs against PatchCollector; this adapter provides the runtime backing.
 */
import PatchCollector from "../capabilities/PatchCollector.js";
function isProvenanceIndexShape(value) {
    if (value === null || value === undefined || typeof value !== 'object') {
        return false;
    }
    return (typeof Reflect.get(value, 'clone') === 'function' &&
        typeof Reflect.get(value, 'addPatch') === 'function');
}
function toCheckpointData(checkpoint) {
    if (checkpoint === null) {
        return null;
    }
    return {
        state: checkpoint.state,
        frontier: checkpoint.frontier,
        stateHash: checkpoint.stateHash,
        schema: checkpoint.schema,
        ...(isProvenanceIndexShape(checkpoint.provenanceIndex)
            ? { provenanceIndex: checkpoint.provenanceIndex }
            : {}),
        ...(checkpoint.indexShardOids !== undefined ? { indexShardOids: checkpoint.indexShardOids } : {}),
    };
}
function toRuntimeCheckpointData(checkpoint) {
    return {
        state: checkpoint.state,
        frontier: checkpoint.frontier,
        stateHash: checkpoint.stateHash,
        schema: checkpoint.schema,
        ...(checkpoint.provenanceIndex !== undefined ? { provenanceIndex: checkpoint.provenanceIndex } : {}),
        ...(checkpoint.indexShardOids !== undefined ? { indexShardOids: checkpoint.indexShardOids } : {}),
    };
}
export default class RuntimePatchCollector extends PatchCollector {
    _runtime;
    constructor(runtime) {
        super();
        this._runtime = runtime;
    }
    async discoverWriters() {
        return await this._runtime.discoverWriters();
    }
    async loadWriterPatches(writerId) {
        return await this._runtime._loadWriterPatches(writerId);
    }
    async *streamForFrontier(frontier, ceiling) {
        for (const writerId of frontier.keys()) {
            const tipSha = frontier.get(writerId);
            if (typeof tipSha !== 'string' || tipSha.length === 0) {
                continue;
            }
            const patches = await this._runtime._loadPatchChainFromSha(tipSha);
            for (const entry of patches) {
                if (ceiling === null || entry.patch.lamport <= ceiling) {
                    yield entry;
                }
            }
        }
    }
    async loadCheckpoint() {
        return toCheckpointData(await this._runtime._loadLatestCheckpoint());
    }
    async loadPatchesSince(checkpoint) {
        return await this._runtime._loadPatchesSince(toRuntimeCheckpointData(checkpoint));
    }
    async loadPatchChain(toSha, fromSha) {
        return await this._runtime._loadPatchChainFromSha(toSha, fromSha);
    }
    async getFrontier() {
        return await this._runtime.getFrontier();
    }
}
