"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseCsv = void 0;
exports.parseCsvRecords = parseCsvRecords;
/**
 * 将 CSV 文本切分为二维字符串表（每行字段数组）。
 * @param delimiter 字段分隔符，常见 `,` 或 `;`
 */
function parseCsvRecords(content, delimiter) {
    const rows = [];
    let row = [];
    let field = '';
    let inQuotes = false;
    let i = 0;
    const len = content.length;
    const flushField = () => {
        row.push(field);
        field = '';
    };
    const flushRow = () => {
        flushField();
        rows.push(row);
        row = [];
    };
    while (i < len) {
        const c = content[i];
        if (inQuotes) {
            if (c === '"') {
                if (i + 1 < len && content[i + 1] === '"') {
                    field += '"';
                    i += 2;
                    continue;
                }
                inQuotes = false;
                i++;
                continue;
            }
            field += c;
            i++;
            continue;
        }
        if (c === '"') {
            inQuotes = true;
            i++;
            continue;
        }
        if (c === delimiter) {
            flushField();
            i++;
            continue;
        }
        if (c === '\r') {
            i++;
            if (i < len && content[i] === '\n') {
                i++;
            }
            flushRow();
            continue;
        }
        if (c === '\n') {
            i++;
            flushRow();
            continue;
        }
        field += c;
        i++;
    }
    flushField();
    rows.push(row);
    while (rows.length > 1 && rows[rows.length - 1].every((f) => f === '')) {
        rows.pop();
    }
    if (rows.length === 0) {
        return [['']];
    }
    return rows;
}
function sheetNameFromSuggestedName(suggested) {
    const hint = suggested?.trim() ?? '';
    if (!hint)
        return 'Sheet1';
    const base = hint.includes('/') ? hint.split('/').pop() ?? hint : hint;
    const noExt = base.replace(/\.[^./\\]+$/u, '').trim();
    return noExt.length > 0 ? noExt : 'Sheet1';
}
/**
 * 将 CSV buffer 解析为 OfficeParserAST（`type: 'csv'`）。
 */
const parseCsv = async (buffer, config) => {
    const delim = typeof config.csvDelimiter === 'string' &&
        config.csvDelimiter.length > 0
        ? config.csvDelimiter
        : ',';
    let text = buffer.toString('utf8');
    if (text.length > 0 && text.charCodeAt(0) === 0xfeff) {
        text = text.slice(1);
    }
    const grid = parseCsvRecords(text, delim);
    const maxCols = grid.reduce((m, r) => Math.max(m, r.length), 0);
    const padded = grid.map((r) => {
        if (r.length >= maxCols)
            return r;
        return [...r, ...Array(maxCols - r.length).fill('')];
    });
    const rows = [];
    for (let r = 0; r < padded.length; r++) {
        const line = padded[r];
        const cells = [];
        for (let c = 0; c < line.length; c++) {
            const val = line[c] ?? '';
            cells.push({
                type: 'cell',
                text: val,
                children: [{ type: 'text', text: val, formatting: {} }],
                metadata: { row: r, col: c },
            });
        }
        rows.push({ type: 'row', children: cells });
    }
    const sheetName = sheetNameFromSuggestedName(config.suggestedFileName);
    const content = [
        {
            type: 'sheet',
            children: rows,
            metadata: { sheetName },
        },
    ];
    const metadata = {};
    const nl = config.newlineDelimiter ?? '\n';
    return {
        type: 'csv',
        metadata,
        content,
        attachments: [],
        toText: () => padded.map((line) => line.join(delim)).join(nl),
    };
};
exports.parseCsv = parseCsv;
