import { readFile } from 'node:fs/promises';
import { z } from 'zod';
import { wrapDependencyLoadError } from '../utils.js';
const XlsxWorkbookSchema = z.object({
    SheetNames: z.array(z.string()),
    Sheets: z.record(z.string(), z
        .object({
        '!ref': z.string().optional(),
    })
        .passthrough()),
});
// Lazy-loaded so importing this module never pulls in xlsx.
// CJS interop: prefer .default (full API object) and fall back to the namespace.
let xlsxModule;
async function loadXlsx() {
    xlsxModule ??= import('xlsx')
        .then(mod => mod.default ?? mod)
        .catch((error) => wrapDependencyLoadError('xlsx', error));
    return xlsxModule;
}
export async function parseXlsx(filePath) {
    const buffer = await readFile(filePath);
    const XLSX = await loadXlsx();
    const workbook = XlsxWorkbookSchema.parse(XLSX.read(buffer, { type: 'buffer' }));
    const sheets = workbook.SheetNames.length;
    let rows = 0;
    let cells = 0;
    for (const name of workbook.SheetNames) {
        const sheet = workbook.Sheets[name];
        const ref = sheet['!ref'];
        if (!ref)
            continue;
        const range = XLSX.utils.decode_range(ref);
        rows += range.e.r - range.s.r + 1;
        cells += (range.e.r - range.s.r + 1) * (range.e.c - range.s.c + 1);
    }
    return {
        fileType: 'Excel',
        metrics: { sheets, rows, cells },
        confidence: {
            sheets: 'exact',
            rows: 'exact',
            cells: 'exact',
        },
    };
}
//# sourceMappingURL=xlsx.js.map