var __awaiter = this && this.__awaiter || function(thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))((function(resolve, reject) {
        function fulfilled(value) {
            try {
                step(generator.next(value));
            } catch (e) {
                reject(e);
            }
        }
        function rejected(value) {
            try {
                step(generator.throw(value));
            } catch (e) {
                reject(e);
            }
        }
        function step(result) {
            var value;
            result.done ? resolve(result.value) : (value = result.value, value instanceof P ? value : new P((function(resolve) {
                resolve(value);
            }))).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    }));
};

import { FormulaEngine } from "../formula/formula-engine";

import { FormulaRangeSelector } from "../formula/formula-range-selector";

import { CellHighlightManager } from "../formula";

import { CrossSheetFormulaHandler } from "../formula/cross-sheet-formula-handler";

const DEFAULT_FORMULA_ENGINE_CONFIG = {
    precisionRounding: 14,
    caseSensitive: !1,
    ignoreWhiteSpace: "standard",
    nullDate: {
        year: 1899,
        month: 12,
        day: 30
    },
    dateFormats: [ "DD/MM/YYYY", "DD/MM/YY", "YYYY-MM-DD" ],
    timeFormats: [ "hh:mm", "hh:mm:ss.s" ]
};

export class FormulaManager {
    get formulaWorkingOnCell() {
        return this._formulaWorkingOnCell;
    }
    set formulaWorkingOnCell(value) {
        this._formulaWorkingOnCell = value;
    }
    constructor(sheet) {
        this.sheetMapping = new Map, this.reverseSheetMapping = new Map, this.isInitialized = !1, 
        this.nextSheetId = 0, this._formulaWorkingOnCell = null, this.lastKnownCursorPosInFormulaInput = null, 
        this.lastSelectionRangesOfHandling = [], this.inputIsParamMode = null, this.inputingElement = null, 
        this.creatingSheets = new Set, this.sheet = sheet, this.cellHighlightManager = new CellHighlightManager(sheet), 
        this.formulaRangeSelector = new FormulaRangeSelector(this), this.initializeFormulaEngine(), 
        this.crossSheetHandler = new CrossSheetFormulaHandler(this.formulaEngine, this.sheet.getSheetManager(), this);
    }
    initializeFormulaEngine() {
        try {
            this.formulaEngine = new FormulaEngine(DEFAULT_FORMULA_ENGINE_CONFIG), this.isInitialized = !0;
        } catch (error) {
            throw new Error("FormulaManager initialization failed");
        }
    }
    addSheet(sheetKey, normalizedData, sheetTitle) {
        if (this.ensureInitialized(), this.sheetMapping.has(sheetKey)) {
            const existingId = this.sheetMapping.get(sheetKey);
            if (void 0 !== existingId) return existingId;
        }
        try {
            const wasFirstSheet = 0 === this.sheetMapping.size, sheetId = this.formulaEngine.addSheet(sheetKey, normalizedData);
            return sheetTitle && this.formulaEngine.setSheetTitle(sheetKey, sheetTitle), this.sheetMapping.set(sheetKey, sheetId), 
            this.reverseSheetMapping.set(sheetId, sheetKey), this.nextSheetId = Math.max(this.nextSheetId, sheetId + 1), 
            wasFirstSheet && this.formulaEngine.setActiveSheet(sheetKey), sheetId;
        } catch (error) {
            throw new Error(`Failed to add sheet: ${sheetKey}`);
        }
    }
    normalizeSheetData(data, tableInstance) {
        try {
            const headerRows = [];
            for (let i = 0; i < tableInstance.columnHeaderLevelCount; i++) {
                const headerRow = [];
                for (let j = 0; j < tableInstance.colCount; j++) {
                    const cellValue = tableInstance.getCellValue(j, i);
                    headerRow.push(cellValue);
                }
                headerRows.push(headerRow);
            }
            const dataCopy = JSON.parse(JSON.stringify(data)), toNormalizeData = tableInstance.columnHeaderLevelCount > 0 ? [ ...headerRows ].concat(dataCopy) : dataCopy;
            if (!Array.isArray(toNormalizeData) || 0 === toNormalizeData.length) return [ [ "" ] ];
            const validData = toNormalizeData.filter((row => Array.isArray(row)));
            if (0 === validData.length) return [ [ "" ] ];
            const maxCols = Math.max(...validData.map((row => row.length)));
            return validData.map((row => {
                const normalizedRow = Array.isArray(row) ? row.map((cell => {
                    if ("string" == typeof cell) {
                        if (cell.startsWith("=")) return cell;
                        const num = Number(cell);
                        return isNaN(num) || "" === cell.trim() ? cell : num;
                    }
                    return null != cell ? cell : "";
                })) : [ "" ];
                for (;normalizedRow.length < maxCols; ) normalizedRow.push("");
                return normalizedRow;
            }));
        } catch (error) {
            return [ [ "" ] ];
        }
    }
    removeSheet(sheetKey) {
        const sheetId = this.sheetMapping.get(sheetKey);
        if (void 0 !== sheetId) try {
            this.formulaEngine.removeSheet(sheetKey), this.sheetMapping.delete(sheetKey), this.reverseSheetMapping.delete(sheetId);
        } catch (error) {
            throw new Error(`Failed to remove sheet: ${sheetKey}`);
        }
    }
    renameSheet(oldKey, newKey) {
        const sheetId = this.sheetMapping.get(oldKey);
        if (void 0 === sheetId) throw new Error(`Sheet not found: ${oldKey}`);
        try {
            this.formulaEngine.renameSheet(oldKey, newKey), this.sheetMapping.delete(oldKey), 
            this.sheetMapping.set(newKey, sheetId), this.reverseSheetMapping.set(sheetId, newKey);
        } catch (error) {
            throw new Error(`Failed to rename sheet: ${oldKey}`);
        }
    }
    updateSheetTitle(sheetKey, newTitle) {
        const oldTitle = this.formulaEngine.getSheetTitle(sheetKey);
        this.formulaEngine.setSheetTitle(sheetKey, newTitle), oldTitle && oldTitle !== newTitle && this.updateCrossSheetFormulasWithNewTitle(oldTitle, newTitle), 
        this.crossSheetHandler && this.crossSheetHandler.clearCache();
    }
    updateCrossSheetFormulasWithNewTitle(oldTitle, newTitle) {
        try {
            const allSheets = this.sheet.getSheetManager().getAllSheets();
            for (const sheetInfo of allSheets) {
                const formulas = this.formulaEngine.exportFormulas(sheetInfo.sheetKey);
                for (const [cellRef, formula] of Object.entries(formulas)) if (this.hasCrossSheetReference(formula)) {
                    const escapedOldTitle = oldTitle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), patterns = [ `${escapedOldTitle}!`, `${escapedOldTitle}！`, `'${escapedOldTitle}'!`, `'${escapedOldTitle}'！` ];
                    let updatedFormula = formula, hasChanges = !1;
                    for (const pattern of patterns) updatedFormula.includes(pattern) && (pattern.includes(`'${escapedOldTitle}'`) ? pattern.endsWith("!") ? updatedFormula = updatedFormula.replace(new RegExp(`'${escapedOldTitle}'!`, "g"), `'${newTitle}'!`) : pattern.endsWith("！") && (updatedFormula = updatedFormula.replace(new RegExp(`'${escapedOldTitle}'！`, "g"), `'${newTitle}'！`)) : pattern.endsWith("!") ? updatedFormula = updatedFormula.replace(new RegExp(`${escapedOldTitle}!`, "g"), `${newTitle}!`) : pattern.endsWith("！") && (updatedFormula = updatedFormula.replace(new RegExp(`${escapedOldTitle}！`, "g"), `${newTitle}！`)), 
                    hasChanges = !0);
                    if (hasChanges && updatedFormula !== formula) {
                        const cell = this.parseA1CellRef(`${sheetInfo.sheetKey}!${cellRef}`);
                        cell && this.formulaEngine.setCellContent(cell, updatedFormula);
                    }
                }
            }
        } catch (error) {}
    }
    parseA1CellRef(cellRef) {
        try {
            let parts;
            if (parts = cellRef.includes("!") ? cellRef.split("!") : cellRef.includes("！") ? cellRef.split("！") : [ "Sheet1", cellRef ], 
            2 !== parts.length) return null;
            const [sheet, a1Notation] = parts, match = a1Notation.match(/^([A-Z]+)([0-9]+)$/);
            if (!match) return null;
            const colLetters = match[1], rowNumber = parseInt(match[2], 10);
            let col = 0;
            for (let i = 0; i < colLetters.length; i++) col = 26 * col + (colLetters.charCodeAt(i) - 65);
            return {
                sheet: sheet,
                row: rowNumber - 1,
                col: col
            };
        } catch (_a) {
            return null;
        }
    }
    ensureSheetRegistered(sheetKey) {
        if (this.sheet.workSheetInstances.has(sheetKey)) return;
        if (this.creatingSheets.has(sheetKey)) return;
        const sheetDefine = this.sheet.getSheetManager().getSheet(sheetKey);
        if (sheetDefine) try {
            this.creatingSheets.add(sheetKey);
            const instance = this.sheet.createWorkSheetInstance(sheetDefine);
            this.sheet.workSheetInstances.set(sheetKey, instance);
        } finally {
            this.creatingSheets.delete(sheetKey);
        }
    }
    ensureAllSheetsRegisteredForCrossSheetFormula(formula) {
        try {
            const sheetPattern = /([A-Za-z0-9_一-龥]+)!/g;
            let match;
            const referencedSheets = new Set;
            for (;null !== (match = sheetPattern.exec(formula)); ) {
                const sheetName = match[1];
                sheetName && referencedSheets.add(sheetName);
            }
            for (const sheetTitle of referencedSheets) {
                const sheetInfo = this.sheet.getSheetManager().getAllSheets().find((sheet => sheet.sheetTitle.toLowerCase() === sheetTitle.toLowerCase()));
                sheetInfo && this.ensureSheetRegistered(sheetInfo.sheetKey);
            }
        } catch (error) {}
    }
    normalizeDataForFormulaEngine(data) {
        if (!Array.isArray(data) || 0 === data.length) return [ [ "" ] ];
        const maxCols = Math.max(...data.map((row => Array.isArray(row) ? row.length : 0)));
        return data.map((row => {
            if (!Array.isArray(row)) return Array(maxCols).fill("");
            const normalizedRow = row.map((cell => {
                if ("string" == typeof cell) {
                    if (cell.startsWith("=")) return cell;
                    const num = Number(cell);
                    return isNaN(num) || "" === cell.trim() ? cell : num;
                }
                return null != cell ? cell : "";
            }));
            for (;normalizedRow.length < maxCols; ) normalizedRow.push("");
            return normalizedRow;
        }));
    }
    emitFormulaEvent(cell, eventType, formula, error) {
        let worksheet = null;
        if (this.sheet && "function" == typeof this.sheet.getWorkSheetByKey) worksheet = this.sheet.getWorkSheetByKey(cell.sheet); else try {
            const workSheetInstances = this.sheet.workSheetInstances;
            workSheetInstances && workSheetInstances.get && (worksheet = workSheetInstances.get(cell.sheet));
        } catch (_e) {
            return;
        }
        if (worksheet && worksheet.eventManager) switch (eventType) {
          case "added":
            worksheet.eventManager.emitFormulaAdded({
                row: cell.row,
                col: cell.col
            }, formula);
            break;

          case "removed":
            worksheet.eventManager.emitFormulaRemoved({
                row: cell.row,
                col: cell.col
            }, formula);
            break;

          case "error":
            worksheet.eventManager.emitFormulaError(cell, formula || "", error);
        }
    }
    getSheetId(sheetKey) {
        const sheetId = this.sheetMapping.get(sheetKey);
        if (void 0 !== sheetId) return sheetId;
        const lowerSheetKey = sheetKey.toLowerCase();
        for (const [existingKey, existingId] of this.sheetMapping.entries()) if (existingKey.toLowerCase() === lowerSheetKey) return existingId;
        return this.addSheet(sheetKey);
    }
    setCellContent(cell, value) {
        if (this.ensureInitialized(), !cell || void 0 === cell.sheet || void 0 === cell.row || void 0 === cell.col) throw new Error("Invalid cell parameter for setCellContent");
        if (cell.row < 0 || cell.col < 0) throw new Error(`Cell coordinates out of bounds: row=${cell.row}, col=${cell.col}`);
        try {
            this.formulaEngine.setActiveSheet(cell.sheet);
            const isFormula = "string" == typeof value && value.startsWith("="), oldFormula = this.getCellFormula(cell);
            isFormula && this.hasCrossSheetReference(value) ? this.crossSheetHandler.setCrossSheetFormula(cell, value) : this.formulaEngine.setCellContent(cell, value);
            const newFormula = this.getCellFormula(cell);
            newFormula && newFormula !== oldFormula ? this.emitFormulaEvent(cell, "added", newFormula) : !newFormula && oldFormula && this.emitFormulaEvent(cell, "removed", oldFormula);
        } catch (error) {
            throw "string" == typeof value && value.startsWith("=") && this.emitFormulaEvent(cell, "error", value, error), 
            error instanceof Error ? new Error(`Failed to set cell content at ${cell.sheet}:${cell.row}:${cell.col}. ${error.message}`) : new Error(`Failed to set cell content at ${cell.sheet}:${cell.row}:${cell.col}`);
        }
    }
    getCellValue(cell) {
        this.ensureInitialized();
        try {
            const formula = this.formulaEngine.getCellFormula(cell);
            if (formula && this.hasCrossSheetReference(formula)) {
                this.ensureAllSheetsRegisteredForCrossSheetFormula(formula);
                return this.formulaEngine.getCellValue(cell);
            }
            return this.ensureSheetRegistered(cell.sheet), this.formulaEngine.setActiveSheet(cell.sheet), 
            this.formulaEngine.getCellValue(cell);
        } catch (error) {
            return {
                value: null,
                error: error instanceof Error ? error.message : "Unknown error"
            };
        }
    }
    getCellFormula(cell) {
        this.ensureInitialized();
        try {
            return this.formulaEngine.getCellFormula(cell);
        } catch (error) {
            return;
        }
    }
    isCellFormula(cell) {
        this.ensureInitialized();
        try {
            return this.formulaEngine.isCellFormula(cell);
        } catch (error) {
            return !1;
        }
    }
    getCellDependents(cell) {
        this.ensureInitialized();
        try {
            return this.formulaEngine.getCellDependents(cell);
        } catch (error) {
            return [];
        }
    }
    getCellPrecedents(cell) {
        this.ensureInitialized();
        try {
            return this.formulaEngine.getCellPrecedents(cell);
        } catch (error) {
            return [];
        }
    }
    batchUpdate(changes) {
        this.ensureInitialized();
        try {
            for (const {cell: cell, value: value} of changes) this.formulaEngine.setCellContent(cell, value);
        } catch (error) {
            throw new Error("Batch update failed");
        }
    }
    addRows(sheetKey, rowIndex, numberOfRows = 1) {
        this.ensureInitialized();
        try {
            const {adjustedCells: adjustedCells, movedCells: movedCells} = this.formulaEngine.adjustFormulaReferences(sheetKey, "insert", "row", rowIndex, numberOfRows, this.sheet.getSheet(sheetKey).columnCount, this.sheet.getSheet(sheetKey).rowCount);
            [ ...adjustedCells, ...movedCells ].forEach((cell => {
                var _a;
                const result = this.sheet.formulaManager.getCellValue({
                    sheet: sheetKey,
                    row: cell.row,
                    col: cell.col
                });
                null === (_a = this.sheet.getActiveSheet().tableInstance) || void 0 === _a || _a.changeCellValue(cell.col, cell.row, result.error ? "#ERROR!" : result.value, !1, !1);
            }));
        } catch (error) {
            throw new Error(`Failed to add ${numberOfRows} rows at index ${rowIndex}`);
        }
    }
    removeRows(sheetKey, rowIndex, numberOfRows = 1) {
        this.ensureInitialized();
        try {
            const {adjustedCells: adjustedCells, movedCells: movedCells} = this.formulaEngine.adjustFormulaReferences(sheetKey, "delete", "row", rowIndex, numberOfRows, this.sheet.getSheet(sheetKey).columnCount, this.sheet.getSheet(sheetKey).rowCount);
            [ ...adjustedCells, ...movedCells ].forEach((cell => {
                var _a;
                const result = this.sheet.formulaManager.getCellValue({
                    sheet: sheetKey,
                    row: cell.row,
                    col: cell.col
                });
                null === (_a = this.sheet.getActiveSheet().tableInstance) || void 0 === _a || _a.changeCellValue(cell.col, cell.row, result.error ? "#ERROR!" : result.value, !1, !1);
            }));
        } catch (error) {
            throw new Error(`Failed to remove ${numberOfRows} rows at index ${rowIndex}`);
        }
    }
    addColumns(sheetKey, columnIndex, numberOfColumns = 1) {
        this.ensureInitialized();
        try {
            const {adjustedCells: adjustedCells, movedCells: movedCells} = this.formulaEngine.adjustFormulaReferences(sheetKey, "insert", "column", columnIndex, numberOfColumns, this.sheet.getSheet(sheetKey).columnCount, this.sheet.getSheet(sheetKey).rowCount);
            [ ...adjustedCells, ...movedCells ].forEach((cell => {
                var _a;
                const result = this.sheet.formulaManager.getCellValue({
                    sheet: sheetKey,
                    row: cell.row,
                    col: cell.col
                });
                null === (_a = this.sheet.getActiveSheet().tableInstance) || void 0 === _a || _a.changeCellValue(cell.col, cell.row, result.error ? "#ERROR!" : result.value, !1, !1);
            }));
        } catch (error) {
            throw new Error(`Failed to add ${numberOfColumns} columns at index ${columnIndex}`);
        }
    }
    removeColumns(sheetKey, columnIndex, numberOfColumns = 1) {
        this.ensureInitialized();
        try {
            const {adjustedCells: adjustedCells, movedCells: movedCells} = this.formulaEngine.adjustFormulaReferences(sheetKey, "delete", "column", columnIndex, numberOfColumns, this.sheet.getSheet(sheetKey).columnCount, this.sheet.getSheet(sheetKey).rowCount);
            [ ...adjustedCells, ...movedCells ].forEach((cell => {
                var _a;
                const result = this.sheet.formulaManager.getCellValue({
                    sheet: sheetKey,
                    row: cell.row,
                    col: cell.col
                });
                null === (_a = this.sheet.getActiveSheet().tableInstance) || void 0 === _a || _a.changeCellValue(cell.col, cell.row, result.error ? "#ERROR!" : result.value, !1, !1);
            }));
        } catch (error) {
            throw new Error(`Failed to remove ${numberOfColumns} columns at index ${columnIndex}`);
        }
    }
    changeColumnHeaderPosition(sheetKey, sourceCol, targetCol) {
        var _a;
        this.ensureInitialized();
        try {
            const sheet = this.sheet.getSheet(sheetKey);
            if (!sheet) throw new Error(`Sheet not found: ${sheetKey}`);
            const totalColCount = sheet.columnCount, totalRowCount = sheet.rowCount, {adjustedCells: adjustedCells, movedCells: movedCells} = this.formulaEngine.adjustFormulaReferencesForColumnMove(sheetKey, sourceCol, targetCol, totalColCount, totalRowCount), allAffectedCells = [ ...adjustedCells, ...movedCells ];
            for (const cell of allAffectedCells) {
                const result = this.getCellValue(cell);
                null === (_a = this.sheet.getActiveSheet().tableInstance) || void 0 === _a || _a.changeCellValue(cell.col, cell.row, result.error ? "#ERROR!" : result.value, !1, !1);
            }
        } catch (error) {
            throw new Error(`Failed to change column header position: ${error instanceof Error ? error.message : "Unknown error"}`);
        }
    }
    changeRowHeaderPosition(sheetKey, sourceRow, targetRow) {
        var _a;
        this.ensureInitialized();
        try {
            if (!this.sheet.getSheet(sheetKey)) throw new Error(`Sheet not found: ${sheetKey}`);
            const {adjustedCells: adjustedCells, movedCells: movedCells} = this.formulaEngine.adjustFormulaReferencesForRowMove(sheetKey, sourceRow, targetRow), allAffectedCells = [ ...adjustedCells, ...movedCells ];
            for (const cell of allAffectedCells) {
                const result = this.getCellValue(cell);
                null === (_a = this.sheet.getActiveSheet().tableInstance) || void 0 === _a || _a.changeCellValue(cell.col, cell.row, result.error ? "#ERROR!" : result.value, !1, !1);
            }
        } catch (error) {
            throw new Error(`Failed to change row header position: ${error instanceof Error ? error.message : "Unknown error"}`);
        }
    }
    getSheetSerialized(sheetKey) {
        this.ensureInitialized();
        try {
            return [ [] ];
        } catch (error) {
            return [ [] ];
        }
    }
    sortFormulasByDependency(sheetKey, formulas) {
        try {
            return this.formulaEngine.sortFormulasByDependency(sheetKey, formulas);
        } catch (_error) {
            return Object.entries(formulas);
        }
    }
    hasCircularReference() {
        try {
            return !1;
        } catch (error) {
            return !1;
        }
    }
    getAvailableFunctions() {
        return [ "ABS", "ACOS", "AND", "ASIN", "ATAN", "AVERAGE", "CEILING", "CONCATENATE", "COS", "COUNT", "COUNTA", "COUNTIF", "COUNTIFS", "DATE", "DAY", "FLOOR", "IF", "IFERROR", "INDEX", "LEFT", "LEN", "LOWER", "MATCH", "MAX", "MID", "MIN", "MONTH", "NOT", "NOW", "OR", "RIGHT", "ROUND", "ROUNDDOWN", "ROUNDUP", "SIN", "SUM", "SUMIF", "SUMIFS", "TAN", "TODAY", "UPPER", "VLOOKUP", "YEAR" ];
    }
    validateFormula(formula) {
        try {
            return this.formulaEngine.validateFormula(formula);
        } catch (error) {
            return {
                isValid: !1,
                error: error instanceof Error ? error.message : "Invalid formula syntax"
            };
        }
    }
    isFormulaComplete(formula) {
        if (!formula || "string" != typeof formula) return !1;
        if (!formula.startsWith("=")) return !0;
        if ("=" === formula.trim()) return !1;
        try {
            const openParenCount = (formula.match(/\(/g) || []).length, closeParenCount = (formula.match(/\)/g) || []).length, doubleQuoteCount = (formula.match(/"/g) || []).length, singleQuoteCount = (formula.match(/'/g) || []).length;
            if (openParenCount !== closeParenCount || doubleQuoteCount % 2 != 0 || singleQuoteCount % 2 != 0) return !1;
            if (formula.match(/\([^)]*,\s*\)/) || formula.match(/,\s*\)/) || formula.match(/\(\s*\)/) || formula.endsWith(",")) return !1;
            if (formula.match(/,,/)) return !1;
            if (formula.match(/[+\-*/^&%<>=]$/)) return !1;
            if (formula.match(/[<>=][<>=]?(?=[\s,)])/)) return !1;
            if (formula.match(/\b(AND|OR|NOT)\((?=[\s,)])/i)) return !1;
            if (formula.match(/[+\-*/^&%][+\-*/^&%]/)) return !1;
            return this.validateFormula(formula).isValid;
        } catch (_error) {
            return !1;
        }
    }
    calculateFormula(formula) {
        try {
            return this.hasCrossSheetReference(formula) && this.ensureAllSheetsRegisteredForCrossSheetFormula(formula), 
            this.formulaEngine.calculateFormula(formula);
        } catch (error) {
            return {
                value: null,
                error: error instanceof Error ? error.message : "Calculation failed"
            };
        }
    }
    suspendEvaluation() {}
    resumeEvaluation() {}
    rebuildFormulas(sheets) {
        try {
            if (this.formulaEngine) try {
                this.formulaEngine.release();
            } catch (error) {}
            if (this.sheetMapping.clear(), this.reverseSheetMapping.clear(), this.nextSheetId = 0, 
            this.initializeFormulaEngine(), this.crossSheetHandler) try {
                this.crossSheetHandler.destroy();
            } catch (error) {}
            this.crossSheetHandler = new CrossSheetFormulaHandler(this.formulaEngine, this.sheet.getSheetManager(), this), 
            sheets.forEach((sheetDefine => {
                const sheetKey = sheetDefine.sheetKey, worksheetInstance = this.sheet.workSheetInstances.get(sheetKey);
                if (!worksheetInstance || !worksheetInstance.tableInstance) return;
                const normalizedData = this.normalizeSheetData(worksheetInstance.getData(), worksheetInstance.tableInstance);
                this.addSheet(sheetKey, normalizedData, sheetDefine.sheetTitle);
            }));
        } catch (error) {}
    }
    rebuildAndRecalculate() {}
    clearContent() {
        try {
            this.release(), this.initializeFormulaEngine();
        } catch (error) {}
    }
    release() {
        var _a, _b, _c;
        null === (_a = this.formulaRangeSelector) || void 0 === _a || _a.release(), null === (_b = this.cellHighlightManager) || void 0 === _b || _b.release(), 
        null === (_c = this.crossSheetHandler) || void 0 === _c || _c.destroy();
        try {
            this.formulaEngine && this.formulaEngine.release();
        } catch (error) {} finally {
            this.sheetMapping.clear(), this.reverseSheetMapping.clear(), this.isInitialized = !1, 
            this.nextSheetId = 0, this.formulaRangeSelector = null, this.cellHighlightManager = null;
        }
    }
    exportState() {
        return {
            isInitialized: this.isInitialized,
            sheets: Array.from(this.sheetMapping.entries()),
            functions: this.getAvailableFunctions(),
            crossSheetHandler: this.crossSheetHandler ? this.crossSheetHandler.getHandlerStatus() : null,
            stats: null
        };
    }
    exportFormulas(sheetKey) {
        this.ensureInitialized();
        try {
            return this.formulaEngine.exportFormulas(sheetKey);
        } catch (error) {
            return {};
        }
    }
    ensureInitialized() {
        if (!this.isInitialized) throw new Error("FormulaManager not initialized");
    }
    getAllSheets() {
        try {
            return this.formulaEngine.getAllSheets();
        } catch (error) {
            return [];
        }
    }
    setActiveSheet(sheetKey) {
        this.ensureInitialized();
        try {
            this.formulaEngine.setActiveSheet(sheetKey);
        } catch (error) {
            throw new Error(`Failed to set active sheet: ${sheetKey}`);
        }
    }
    getActiveSheet() {
        this.ensureInitialized();
        try {
            return this.formulaEngine.getActiveSheet();
        } catch (error) {
            return null;
        }
    }
    copyRange(sourceSheet, sourceRange, targetSheet, targetRow, targetCol) {
        this.ensureInitialized();
        try {
            for (let row = sourceRange.startRow; row <= sourceRange.endRow; row++) for (let col = sourceRange.startCol; col <= sourceRange.endCol; col++) {
                const sourceCell = {
                    sheet: sourceSheet,
                    row: row,
                    col: col
                }, targetCell = {
                    sheet: targetSheet,
                    row: targetRow + (row - sourceRange.startRow),
                    col: targetCol + (col - sourceRange.startCol)
                }, value = this.getCellValue(sourceCell).value;
                null != value && this.setCellContent(targetCell, value);
            }
        } catch (error) {
            throw new Error("Failed to copy cell range");
        }
    }
    hasCrossSheetReference(formula) {
        return formula.includes("!") || formula.includes("！");
    }
    getCrossSheetDependencies() {
        return this.crossSheetHandler.getCrossSheetDependencies();
    }
    validateCrossSheetFormula(cell) {
        return this.crossSheetHandler.validateCrossSheetFormula(cell);
    }
    validateAllCrossSheetFormulas() {
        return this.crossSheetHandler.validateAllCrossSheetFormulas();
    }
    recalculateAllCrossSheetFormulas() {
        return __awaiter(this, void 0, void 0, (function*() {
            yield this.crossSheetHandler.recalculateAllCrossSheetFormulas();
        }));
    }
    updateCrossSheetOptions(options) {
        this.crossSheetHandler.updateOptions(options);
    }
}
//# sourceMappingURL=formula-manager.js.map