import { ValueTag } from '@bilig/protocol';
import { DirectFormulaIndexCollection } from './direct-formula-index-collection.js';
import { composeSingleDisjointExplicitEventChanges, countDirectFormulaDeltaSkip, hasCompleteDirectFormulaDeltas, } from './direct-formula-recalc-helpers.js';
import { canTrustPhysicalTrackedChangeSplit, makeCompactExistingNumericMutationResult, makeExistingNumericMutationResult, tagTrustedPhysicalTrackedChanges, } from './operation-change-helpers.js';
import { emitOperationTrackedCellsBatch } from './operation-tracked-event-helpers.js';
export function tryApplyTrustedDirectScalarClosureExistingNumericMutation(args, request) {
    const postRecalcDirectFormulaIndices = new DirectFormulaIndexCollection();
    const oldValue = { tag: ValueTag.Number, value: request.oldNumber };
    const newValue = { tag: ValueTag.Number, value: request.value };
    if (!args.tryMarkDirectScalarLinearDeltaClosure(request.existingIndex, oldValue, newValue, postRecalcDirectFormulaIndices)) {
        return null;
    }
    if (!hasCompleteDirectFormulaDeltas(postRecalcDirectFormulaIndices)) {
        return null;
    }
    countDirectFormulaDeltaSkip(args.state.formulas, postRecalcDirectFormulaIndices, args.state.counters);
    args.writeTrustedExistingNumericLiteralToCell(request.existingIndex, request.sheet, request.col, request.value);
    const directChanged = args.tryApplyDirectScalarDeltas(postRecalcDirectFormulaIndices, true);
    if (directChanged === undefined) {
        throw new Error('Failed to apply direct scalar closure delta');
    }
    args.deferSingleCellKernelSync(request.existingIndex);
    const lastMetrics = args.makeSingleLiteralSkipMetrics();
    args.state.setLastMetrics(lastMetrics);
    if (!request.hasTrackedEventListeners && directChanged.length === 1) {
        const formulaCellIndex = directChanged[0];
        const cellStore = args.state.workbook.cellStore;
        return makeCompactExistingNumericMutationResult(request.existingIndex, formulaCellIndex, 1, cellStore.tags[formulaCellIndex] === ValueTag.Number ? cellStore.numbers[formulaCellIndex] : undefined, cellStore.rows[formulaCellIndex] ?? 0, cellStore.cols[formulaCellIndex] ?? 0);
    }
    const changed = composeSingleDisjointExplicitEventChanges(request.existingIndex, directChanged);
    if (changed.length > 4 && canTrustPhysicalTrackedChangeSplit(changed, request.sheetId, 1, args.state.workbook)) {
        tagTrustedPhysicalTrackedChanges(changed, request.sheetId, 1);
    }
    if (request.hasTrackedEventListeners) {
        emitOperationTrackedCellsBatch({
            events: args.state.events,
            changedCellIndices: changed,
            metrics: lastMetrics,
        });
    }
    return makeExistingNumericMutationResult(changed, 1);
}
//# sourceMappingURL=operation-direct-scalar-closure-fast-path.js.map