import Papa from 'papaparse';
function toParseResult(data) {
    if (!data || data.length === 0) {
        return { headers: [], rows: [] };
    }
    const headers = data[0];
    const rows = data
        .slice(1)
        .filter((row) => row.some((cell) => String(cell).trim() !== ''));
    return { headers, rows };
}
function parseWith(content, extra) {
    const result = Papa.parse(content, {
        // Fix the delimiter to a comma rather than letting papaparse auto-detect:
        // detection fails on single-column files (`UndetectableDelimiter`), and the
        // import format is comma-separated anyway.
        delimiter: ',',
        skipEmptyLines: true,
        ...extra,
    });
    // `FieldMismatch` (a row with too few/many cells) is recoverable — papaparse
    // still returns the row's data, and the rewrite/consumer pads or ignores
    // extras. Treat only other error types as fatal.
    const fatalErrors = result.errors.filter((error) => error.type !== 'FieldMismatch');
    if (fatalErrors.length > 0) {
        return {
            code: 'PARSE_ERROR',
        };
    }
    return toParseResult(result.data);
}
export function parseCsv(content) {
    return parseWith(content, {});
}
/**
 * Parses only the header row plus up to `maxRows` data rows — enough to drive
 * the mapping UI and column type detection without reading the whole file
 * (plan D1). Uses papaparse `preview` so parsing stops early instead of
 * parsing everything and slicing.
 */
export function parseCsvSample(content, maxRows) {
    // `preview` counts the header row, so add one to keep `maxRows` data rows.
    return parseWith(content, { preview: maxRows + 1 });
}
export function unparseCsv(headers, rows) {
    return Papa.unparse([headers, ...rows]);
}
//# sourceMappingURL=parseCsv.js.map