/**
 * errorCheck — scan workbook for Excel error values.
 *
 * Ported from client/shared/src/lib/spreadsheet/error-check/error-checker.ts
 * and client/shared/src/lib/spreadsheet/spreadjs/workbook/WorkbookProxy.ts.
 *
 * Runs entirely on top of the SDK's Workbook/Worksheet API — no SpreadJS dependency.
 */
import { isExcelError } from '../cell-diff/types.js';
import { extractSheetAndAddress, parseRange, toExcelAddress } from './address-utils.js';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const MAX_PER_CATEGORY = 10;
// ---------------------------------------------------------------------------
// Core error scanner
// ---------------------------------------------------------------------------
function isError(val) {
    return isExcelError(val) ? val : null;
}
function checkSheetErrors(sheetName, values, startRow, startCol) {
    const rows = values.length;
    const cols = values[0]?.length ?? 0;
    if (rows === 0 || cols === 0)
        return null;
    const errors = [];
    for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
            const errStr = isError(values[r][c]);
            if (errStr) {
                errors.push(`${sheetName}!${toExcelAddress(r + startRow, c + startCol)}: ${errStr}`);
            }
        }
    }
    if (errors.length === 0)
        return null;
    const shown = errors.slice(0, MAX_PER_CATEGORY);
    const lines = [`Errors (${errors.length}):`, ...shown.map((s) => `  ${s}`)];
    if (errors.length > MAX_PER_CATEGORY) {
        lines.push(`  ... and ${errors.length - MAX_PER_CATEGORY} more`);
    }
    return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
 * Check workbook for error values (#REF!, #DIV/0!, #NAME?, etc.).
 *
 * @param wb - The workbook to check.
 * @param ranges - Optional list of targets. Each is either a sheet name ("Sheet1")
 *   to scan the entire sheet, or a range with sheet name ("Sheet1!A1:D50").
 *   If omitted, checks all sheets.
 * @returns Formatted error summary, or "No issues found."
 */
export async function errorCheck(wb, ranges) {
    const targets = ranges ?? (await wb.getSheetNames());
    const results = [];
    for (const target of targets) {
        const { sheetName: extractedSheet, rest } = extractSheetAndAddress(target);
        const hasExplicitRange = extractedSheet != null && rest.includes(':');
        const sheetName = extractedSheet ?? target;
        let ws;
        try {
            ws = await wb.getSheetByName(sheetName);
        }
        catch {
            continue; // sheet not found, skip
        }
        if (hasExplicitRange) {
            // Explicit range — read just that range
            const parsed = parseRange(target);
            const rangeData = await ws.getRange(rest);
            // getRange returns CellData[][], extract values
            const values = rangeData.map((row) => row.map((cell) => cell?.value ?? null));
            const result = checkSheetErrors(sheetName, values, parsed.startRow, parsed.startCol);
            if (result)
                results.push(result);
        }
        else {
            // Whole sheet — use getData
            const usedRange = await ws.getUsedRange();
            if (!usedRange)
                continue;
            const data = await ws.getData();
            const result = checkSheetErrors(sheetName, data, 0, 0);
            if (result)
                results.push(result);
        }
    }
    if (results.length === 0)
        return 'No issues found.';
    return results.join('\n\n');
}
//# sourceMappingURL=error-check.js.map