import type { CellRangeRef, CellValue, ErrorCode, LiteralInput, RecalcMetrics, SelectionState, SyncState, WorkbookPivotSnapshot, WorkbookSnapshot } from '@bilig/protocol';
import type { CompiledFormula, StructuralAxisTransform } from '@bilig/formula';
import type { EngineOp, EngineOpBatch } from '@bilig/workbook';
import type { OpOrder, ReplicaSnapshot, ReplicaState, ReplicaVersionSnapshot } from '../replica-state.js';
import type { EdgeSlice } from '../edge-arena.js';
import type { EngineEventBus } from '../events.js';
import type { FormulaTable } from '../formula-table.js';
import type { CellMutationTransactionRecord } from '../history/typed-history.js';
import type { RangeRegistry } from '../range-registry.js';
import type { RecalcScheduler } from '../scheduler.js';
import type { StringPool } from '../string-pool.js';
import type { WasmKernelFacade } from '../wasm-facade.js';
import type { WorkbookStore } from '../workbook-store.js';
import type { EngineCounters } from '../perf/engine-counters.js';
export declare const INLINE_SCALAR_FAST_PLAN_ARITHMETIC = 1;
export declare const INLINE_SCALAR_FAST_PLAN_LEN = 2;
export declare const INLINE_SCALAR_FAST_PLAN_CONCAT = 3;
export declare const INLINE_SCALAR_FAST_PLAN_MIN_MAX = 4;
export declare const INLINE_SCALAR_FAST_PLAN_ROUND_SQRT = 5;
export declare const INLINE_SCALAR_FAST_PLAN_PMT = 6;
export declare const INLINE_SCALAR_FAST_PLAN_IF_STRING = 7;
export type InlineScalarFastPlanKind = typeof INLINE_SCALAR_FAST_PLAN_ARITHMETIC | typeof INLINE_SCALAR_FAST_PLAN_LEN | typeof INLINE_SCALAR_FAST_PLAN_CONCAT | typeof INLINE_SCALAR_FAST_PLAN_MIN_MAX | typeof INLINE_SCALAR_FAST_PLAN_ROUND_SQRT | typeof INLINE_SCALAR_FAST_PLAN_PMT | typeof INLINE_SCALAR_FAST_PLAN_IF_STRING;
export interface CommitOp {
    kind: 'upsertWorkbook' | 'upsertSheet' | 'renameSheet' | 'deleteSheet' | 'upsertCell' | 'deleteCell';
    name?: string;
    oldName?: string;
    newName?: string;
    order?: number;
    sheetName?: string;
    addr?: string;
    value?: LiteralInput;
    formula?: string;
    format?: string;
}
export interface SpreadsheetEngineOptions {
    workbookName?: string;
    replicaId?: string;
    useColumnIndex?: boolean;
    trackReplicaVersions?: boolean;
    initialCellCapacity?: number;
    evaluationTimeoutMs?: number;
}
export interface EngineSyncClientConnection {
    send(batch: EngineOpBatch): void | Promise<void>;
    disconnect(): void | Promise<void>;
}
export interface EngineSyncClient {
    connect(handlers: {
        applyRemoteBatch(batch: EngineOpBatch): boolean;
        applyRemoteSnapshot?(snapshot: WorkbookSnapshot): void;
        setState(state: SyncState): void;
    }): EngineSyncClientConnection | Promise<EngineSyncClientConnection>;
}
export interface EngineReplicaSnapshot {
    replica: ReplicaSnapshot;
    entityVersions: ReplicaVersionSnapshot[];
    sheetDeleteVersions: Array<{
        sheetName: string;
        order: OpOrder;
    }>;
}
export type TransactionRecord = {
    kind: 'ops';
    ops: EngineOp[];
    potentialNewCells?: number;
    preparedCellAddressesByOpIndex?: readonly (PreparedCellAddress | null)[];
} | {
    kind: 'single-op';
    op: EngineOp;
    potentialNewCells?: number;
    preparedCellAddress?: PreparedCellAddress | null;
} | {
    kind: 'rename-sheet';
    oldName: string;
    newName: string;
    potentialNewCells?: number;
} | {
    kind: 'single-existing-numeric-cell-mutation';
    sheetId: number;
    row: number;
    col: number;
    cellIndex: number;
    value: number;
    potentialNewCells?: number;
} | {
    kind: 'single-existing-literal-cell-mutation';
    sheetId: number;
    row: number;
    col: number;
    cellIndex: number;
    value: LiteralInput;
    potentialNewCells?: number;
} | {
    kind: 'existing-numeric-cell-mutations';
    sheetIds: Uint32Array;
    cellIndexPlusOnes: Uint32Array;
    rows: Uint32Array;
    cols: Uint32Array;
    numbers: Float64Array;
    potentialNewCells?: number;
} | CellMutationTransactionRecord;
export interface TransactionLogEntry {
    forward: TransactionRecord;
    inverse: TransactionRecord;
}
export interface PreparedCellAddress {
    readonly row: number;
    readonly col: number;
}
export interface PreparedExactVectorLookup {
    sheetName: string;
    rowStart: number;
    rowEnd: number;
    col: number;
    length: number;
    columnVersion: number;
    structureVersion: number;
    sheetColumnVersions: Uint32Array;
    comparableKind: 'numeric' | 'text' | 'mixed';
    uniformStart: number | undefined;
    uniformStep: number | undefined;
    firstPositions: Map<string, number>;
    lastPositions: Map<string, number>;
    firstNumericPositions: Map<number, number> | undefined;
    lastNumericPositions: Map<number, number> | undefined;
    firstTextPositions: Map<string, number> | undefined;
    lastTextPositions: Map<string, number> | undefined;
    internalOwner?: unknown;
}
export interface PreparedApproximateVectorLookup {
    sheetName: string;
    rowStart: number;
    rowEnd: number;
    col: number;
    length: number;
    columnVersion: number;
    structureVersion: number;
    sheetColumnVersions: Uint32Array;
    comparableKind: 'numeric' | 'text' | undefined;
    uniformStart: number | undefined;
    uniformStep: number | undefined;
    repeatedUniformStart: number | undefined;
    repeatedUniformStep: number | undefined;
    repeatedUniformRunLength: number | undefined;
    sortedAscending: boolean;
    sortedDescending: boolean;
    numericValues: Float64Array | undefined;
    textValues: string[] | undefined;
    internalOwner?: unknown;
}
export interface RuntimeUniformLookupTailPatch {
    readonly row: number;
    readonly oldNumeric: number;
    readonly newNumeric: number;
    readonly columnVersion: number;
}
export type RuntimeDirectLookupDescriptor = {
    kind: 'exact';
    operandCellIndex: number;
    prepared: PreparedExactVectorLookup;
    searchMode: 1 | -1;
} | {
    kind: 'exact-uniform-numeric';
    operandCellIndex: number;
    sheetName: string;
    sheetId: number;
    rowStart: number;
    rowEnd: number;
    col: number;
    length: number;
    columnVersion: number;
    structureVersion: number;
    sheetColumnVersions: Uint32Array;
    start: number;
    step: number;
    searchMode: 1 | -1;
    tailPatch?: RuntimeUniformLookupTailPatch;
} | {
    kind: 'approximate';
    operandCellIndex: number;
    prepared: PreparedApproximateVectorLookup;
    matchMode: 1 | -1;
} | {
    kind: 'approximate-uniform-numeric';
    operandCellIndex: number;
    sheetName: string;
    sheetId: number;
    rowStart: number;
    rowEnd: number;
    col: number;
    length: number;
    columnVersion: number;
    structureVersion: number;
    sheetColumnVersions: Uint32Array;
    start: number;
    step: number;
    repeatedRunLength?: number;
    matchMode: 1 | -1;
    tailPatch?: RuntimeUniformLookupTailPatch;
};
export interface RuntimeDirectCriteriaRange {
    readonly regionId: number;
    readonly sheetName: string;
    readonly rowStart: number;
    readonly rowEnd: number;
    readonly col: number;
    readonly length: number;
}
export type RuntimeDirectCriteriaOperand = {
    kind: 'literal';
    value: CellValue;
} | {
    kind: 'cell';
    cellIndex: number;
} | {
    kind: 'cell-string-concat';
    cellIndex: number;
    prefix: string;
    suffix: string;
} | {
    kind: 'cell-month-boundary-string-concat';
    cellIndex: number;
    prefix: string;
    suffix: string;
    offsetMonths: number;
};
export interface RuntimeDirectCriteriaPair {
    readonly range: RuntimeDirectCriteriaRange;
    readonly criterion: RuntimeDirectCriteriaOperand;
}
export type RuntimeDirectCriteriaResultTransform = {
    readonly kind: 'round';
    readonly digits: CellValue;
} | {
    readonly kind: 'if-error';
    readonly fallback: CellValue;
} | {
    readonly kind: 'if-empty-cell';
    readonly cellIndex: number;
    readonly fallback: CellValue;
};
export interface RuntimeDirectCriteriaDescriptor {
    readonly aggregateKind: 'count' | 'sum' | 'average' | 'min' | 'max' | 'first';
    readonly aggregateRange: RuntimeDirectCriteriaRange | undefined;
    readonly offsetOperand?: RuntimeDirectScalarOperand;
    readonly firstMatchMode?: 'exact-lookup';
    readonly criteriaPairs: readonly RuntimeDirectCriteriaPair[];
    readonly resultTransforms?: readonly RuntimeDirectCriteriaResultTransform[];
}
export interface RuntimeDirectAggregateDescriptor {
    readonly regionId: number;
    readonly regionIds?: readonly number[];
    readonly aggregateKind: 'sum' | 'average' | 'count' | 'min' | 'max';
    readonly sheetName: string;
    readonly rowStart: number;
    readonly rowEnd: number;
    readonly col: number;
    readonly colEnd: number;
    readonly length: number;
    readonly resultOffset?: number;
}
export type RuntimeDirectScalarOperand = {
    kind: 'cell';
    cellIndex: number;
} | {
    kind: 'error';
    code: ErrorCode;
} | {
    kind: 'literal-number';
    value: number;
};
export type RuntimeDirectScalarDescriptor = {
    kind: 'binary';
    operator: '+' | '-' | '*' | '/';
    left: RuntimeDirectScalarOperand;
    right: RuntimeDirectScalarOperand;
    deltaInputCellIndex?: number;
    resultOffset?: number;
} | {
    kind: 'abs';
    operand: RuntimeDirectScalarOperand;
};
export interface CompiledPlanRecord {
    readonly id: number;
    readonly source: string;
    readonly compiled: CompiledFormula;
    readonly templateId?: number;
}
export interface RuntimeStructuralFormulaSourceTransform {
    readonly ownerSheetName: string;
    readonly targetSheetName: string;
    readonly transform: StructuralAxisTransform;
    readonly preservesValue: boolean;
}
export interface RuntimeSheetRenameFormulaSourceTransform {
    readonly oldSheetName: string;
    readonly newSheetName: string;
}
export interface RuntimeFormula {
    cellIndex: number;
    formulaSlotId: number;
    planId: number;
    templateId: number | undefined;
    source: string;
    compiled: CompiledFormula;
    plan: CompiledPlanRecord;
    dependencyIndices: Uint32Array;
    dependencyEntities: EdgeSlice;
    rangeDependencies: Uint32Array;
    graphRangeDependencies: Uint32Array;
    runtimeProgram: Uint32Array;
    constants: Float64Array;
    structuralSourceTransform: RuntimeStructuralFormulaSourceTransform | undefined;
    sourceRenameTransform?: RuntimeSheetRenameFormulaSourceTransform | undefined;
    sourceRenameTransforms?: RuntimeSheetRenameFormulaSourceTransform[] | undefined;
    programOffset: number;
    programLength: number;
    constNumberOffset: number;
    constNumberLength: number;
    rangeListOffset: number;
    rangeListLength: number;
    directLookup: RuntimeDirectLookupDescriptor | undefined;
    directAggregate: RuntimeDirectAggregateDescriptor | undefined;
    directScalar: RuntimeDirectScalarDescriptor | undefined;
    directCriteria: RuntimeDirectCriteriaDescriptor | undefined;
    preserveCachedValueOnFullRecalc?: boolean;
    inlineScalarFastPlanKind?: InlineScalarFastPlanKind | undefined;
    inlineScalarArithmeticDeltaCoefficients?: Float64Array | undefined;
    inlineScalarPlanCellIndices?: Uint32Array | undefined;
    inlineScalarFastPlanStringIds?: Uint32Array | undefined;
}
export type U32 = Uint32Array;
export declare const UNRESOLVED_WASM_OPERAND = 16777215;
export interface MaterializedDependencies {
    dependencyIndices: Uint32Array;
    dependencyEntities: Uint32Array;
    rangeDependencies: Uint32Array;
    graphRangeDependencies: Uint32Array;
    symbolicRangeIndices: U32;
    symbolicRangeCount: number;
    newRangeIndices: U32;
    newRangeCount: number;
}
export interface SpillMaterialization {
    changedCellIndices: number[];
    ownerValue: CellValue;
}
export type PivotTableInput = Omit<WorkbookPivotSnapshot, 'sheetName' | 'address' | 'rows' | 'cols'> & {
    source: CellRangeRef;
};
export interface RecalcVolatileState {
    nowSerial: number;
    randomValues: number[];
    randomCursor: number;
}
export interface EngineRuntimeState {
    readonly workbook: WorkbookStore;
    readonly strings: StringPool;
    readonly events: EngineEventBus;
    readonly ranges: RangeRegistry;
    readonly scheduler: RecalcScheduler;
    readonly wasm: WasmKernelFacade;
    readonly formulas: FormulaTable<RuntimeFormula>;
    readonly directScalarDeltaInputCellIndices: ArrayLike<number | undefined>;
    readonly directScalarDeltaOutputCellIndicesByInput: ArrayLike<number | undefined>;
    readonly replicaState: ReplicaState;
    readonly entityVersions: Map<string, OpOrder>;
    readonly sheetDeleteVersions: Map<string, OpOrder>;
    readonly batchListeners: Set<(batch: EngineOpBatch) => void>;
    readonly selectionListeners: Set<() => void>;
    readonly undoStack: TransactionLogEntry[];
    readonly redoStack: TransactionLogEntry[];
    readonly counters: EngineCounters;
    readonly trackReplicaVersions: boolean;
    getUseColumnIndex(): boolean;
    setUseColumnIndex(enabled: boolean): void;
    getSelection(): SelectionState;
    setSelection(selection: SelectionState): void;
    getSyncState(): SyncState;
    setSyncState(state: SyncState): void;
    getSyncClientConnection(): EngineSyncClientConnection | null;
    setSyncClientConnection(connection: EngineSyncClientConnection | null): void;
    getTransactionReplayDepth(): number;
    setTransactionReplayDepth(depth: number): void;
    setEvaluationTimeoutMs(timeoutMs: number | undefined): void;
    beginEvaluationBudget(startedAtMs: number): void;
    endEvaluationBudget(): void;
    checkEvaluationBudget(stepCost?: number): void;
    getLastMetrics(): RecalcMetrics;
    setLastMetrics(metrics: RecalcMetrics): void;
}
export interface EngineRuntimeStateController {
    readonly workbook: WorkbookStore;
    readonly strings: StringPool;
    readonly events: EngineEventBus;
    readonly ranges: RangeRegistry;
    readonly scheduler: RecalcScheduler;
    readonly wasm: WasmKernelFacade;
    readonly formulas: FormulaTable<RuntimeFormula>;
    readonly directScalarDeltaInputCellIndices: Array<number | undefined>;
    readonly directScalarDeltaOutputCellIndicesByInput: Array<number | undefined>;
    readonly replicaState: ReplicaState;
    readonly entityVersions: Map<string, OpOrder>;
    readonly sheetDeleteVersions: Map<string, OpOrder>;
    readonly batchListeners: Set<(batch: EngineOpBatch) => void>;
    readonly selectionListeners: Set<() => void>;
    readonly undoStack: TransactionLogEntry[];
    readonly redoStack: TransactionLogEntry[];
    readonly counters: EngineCounters;
    readonly trackReplicaVersions: boolean;
    getUseColumnIndex(): boolean;
    setUseColumnIndex(enabled: boolean): void;
    getSelection(): SelectionState;
    setSelection(selection: SelectionState): void;
    getSyncState(): SyncState;
    setSyncState(state: SyncState): void;
    getSyncClientConnection(): EngineSyncClientConnection | null;
    setSyncClientConnection(connection: EngineSyncClientConnection | null): void;
    getTransactionReplayDepth(): number;
    setTransactionReplayDepth(depth: number): void;
    setEvaluationTimeoutMs(timeoutMs: number | undefined): void;
    beginEvaluationBudget(startedAtMs: number): void;
    endEvaluationBudget(): void;
    checkEvaluationBudget(stepCost?: number): void;
    getLastMetrics(): RecalcMetrics;
    setLastMetrics(metrics: RecalcMetrics): void;
}
export declare function createEngineRuntimeState(controller: EngineRuntimeStateController): EngineRuntimeState;
export declare function createInitialSelectionState(): SelectionState;
export declare function createInitialRecalcMetrics(): RecalcMetrics;
