"use strict";
/**
 * CSV class - Cross-Platform Base Implementation
 *
 * Provides CSV read/write functionality for both Node.js and Browser.
 * Node.js version (csv.ts) extends this with file system support.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatCsv = exports.parseCsv = exports.CsvFormatterStream = exports.CsvParserStream = exports.CSV = void 0;
exports.createDefaultValueMapper = createDefaultValueMapper;
exports.createDefaultWriteMapper = createDefaultWriteMapper;
exports.parseCsvToWorksheet = parseCsvToWorksheet;
exports.formatWorksheetToCsv = formatWorksheetToCsv;
const datetime_1 = require("../../utils/datetime.js");
const csv_core_1 = require("./csv-core.js");
const csv_stream_1 = require("./csv-stream.js");
const csv_number_1 = require("./csv-number.js");
const _stream_1 = require("../stream/index.js");
// =============================================================================
// Constants
// =============================================================================
const DEFAULT_DATE_FORMATS = [
    "YYYY-MM-DD[T]HH:mm:ssZ",
    "YYYY-MM-DD[T]HH:mm:ss",
    "MM-DD-YYYY",
    "YYYY-MM-DD"
];
// =============================================================================
// Value Mappers
// =============================================================================
const SpecialValues = {
    true: true,
    false: false,
    "#N/A": { error: "#N/A" },
    "#REF!": { error: "#REF!" },
    "#NAME?": { error: "#NAME?" },
    "#DIV/0!": { error: "#DIV/0!" },
    "#NULL!": { error: "#NULL!" },
    "#VALUE!": { error: "#VALUE!" },
    "#NUM!": { error: "#NUM!" }
};
function createDefaultValueMapper(dateFormats, options) {
    const dateParser = datetime_1.DateParser.create(dateFormats);
    const decimalSeparator = options?.decimalSeparator ?? ".";
    return function mapValue(datum) {
        if (datum === "") {
            return null;
        }
        if (typeof datum === "string") {
            const datumNumber = (0, csv_number_1.parseNumberFromCsv)(datum, decimalSeparator);
            if (!Number.isNaN(datumNumber) && datumNumber !== Infinity) {
                return datumNumber;
            }
        }
        else {
            const datumNumber = Number(datum);
            if (!Number.isNaN(datumNumber) && datumNumber !== Infinity) {
                return datumNumber;
            }
        }
        const date = dateParser.parse(datum);
        if (date) {
            return date;
        }
        const special = SpecialValues[datum];
        if (special !== undefined) {
            return special;
        }
        return datum;
    };
}
function createDefaultWriteMapper(dateFormat, dateUTC) {
    const formatter = dateFormat
        ? datetime_1.DateFormatter.create(dateFormat, { utc: dateUTC })
        : datetime_1.DateFormatter.iso(dateUTC);
    return function mapValue(value) {
        if (value) {
            if (value.text || value.hyperlink) {
                return value.hyperlink ?? value.text ?? "";
            }
            if (value.formula || value.result) {
                return value.result ?? "";
            }
            if (value instanceof Date) {
                return formatter.format(value);
            }
            if (value.error) {
                return value.error;
            }
            if (typeof value === "object") {
                return JSON.stringify(value);
            }
        }
        return value;
    };
}
// =============================================================================
// CSV Class
// =============================================================================
class CSV {
    constructor(workbook) {
        this.workbook = workbook;
    }
    // ---------------------------------------------------------------------------
    // In-Memory Operations
    // ---------------------------------------------------------------------------
    load(content, options) {
        let str;
        if (typeof content === "string") {
            str = content;
        }
        else if (content instanceof ArrayBuffer || content instanceof Uint8Array) {
            str = new TextDecoder().decode(content);
        }
        else {
            str = String(content);
        }
        const worksheet = this.workbook.addWorksheet(options?.sheetName);
        const dateFormats = options?.dateFormats ?? DEFAULT_DATE_FORMATS;
        const map = options?.map ||
            createDefaultValueMapper(dateFormats, {
                decimalSeparator: options?.valueMapperOptions?.decimalSeparator
            });
        const rows = (0, csv_core_1.parseCsv)(str, options?.parserOptions);
        for (const row of rows) {
            worksheet.addRow(row.map(map));
        }
        return worksheet;
    }
    writeString(options) {
        const worksheet = this.workbook.getWorksheet(options?.sheetName || options?.sheetId);
        if (!worksheet) {
            return "";
        }
        const { dateFormat, dateUTC } = options || {};
        const map = options?.map || createDefaultWriteMapper(dateFormat, dateUTC);
        const includeEmptyRows = options?.includeEmptyRows !== false;
        const rows = [];
        let lastRow = 1;
        worksheet.eachRow((row, rowNumber) => {
            if (includeEmptyRows) {
                while (lastRow++ < rowNumber - 1) {
                    rows.push([]);
                }
            }
            const { values } = row;
            values.shift();
            rows.push(values.map(map));
            lastRow = rowNumber;
        });
        return (0, csv_core_1.formatCsv)(rows, options?.formatterOptions);
    }
    async writeBuffer(options) {
        return new TextEncoder().encode(this.writeString(options));
    }
    // ---------------------------------------------------------------------------
    // Stream Operations
    // ---------------------------------------------------------------------------
    async read(stream, options) {
        const worksheet = this.workbook.addWorksheet(options?.sheetName);
        const dateFormats = options?.dateFormats ?? DEFAULT_DATE_FORMATS;
        const map = options?.map ||
            createDefaultValueMapper(dateFormats, {
                decimalSeparator: options?.valueMapperOptions?.decimalSeparator
            });
        const parser = new csv_stream_1.CsvParserStream(options?.parserOptions);
        return new Promise((resolve, reject) => {
            parser.on("data", (row) => worksheet.addRow(row.map(map)));
            (0, _stream_1.pipeline)(stream, parser)
                .then(() => resolve(worksheet))
                .catch(reject);
        });
    }
    async write(stream, options) {
        const worksheet = this.workbook.getWorksheet(options?.sheetName || options?.sheetId);
        if (!worksheet) {
            stream.end();
            return;
        }
        const { dateFormat, dateUTC } = options || {};
        const map = options?.map || createDefaultWriteMapper(dateFormat, dateUTC);
        const includeEmptyRows = options?.includeEmptyRows !== false;
        const formatterOptions = { ...options?.formatterOptions };
        const formatter = new csv_stream_1.CsvFormatterStream(formatterOptions);
        const pipelinePromise = (0, _stream_1.pipeline)(formatter, stream);
        let lastRow = 1;
        worksheet.eachRow((row, rowNumber) => {
            if (includeEmptyRows) {
                while (lastRow++ < rowNumber - 1) {
                    formatter.write([]);
                }
            }
            const { values } = row;
            values.shift();
            formatter.write(values.map(map));
            lastRow = rowNumber;
        });
        formatter.end();
        await pipelinePromise;
    }
    createReadStream(options) {
        const worksheet = this.workbook.getWorksheet(options?.sheetName || options?.sheetId);
        const { dateFormat, dateUTC } = options || {};
        const map = options?.map || createDefaultWriteMapper(dateFormat, dateUTC);
        const includeEmptyRows = options?.includeEmptyRows !== false;
        const formatter = new csv_stream_1.CsvFormatterStream({ ...options?.formatterOptions });
        if (worksheet) {
            setTimeout(() => {
                let lastRow = 1;
                worksheet.eachRow((row, rowNumber) => {
                    if (includeEmptyRows) {
                        while (lastRow++ < rowNumber - 1) {
                            formatter.write([]);
                        }
                    }
                    const { values } = row;
                    values.shift();
                    formatter.write(values.map(map));
                    lastRow = rowNumber;
                });
                formatter.end();
            }, 0);
        }
        else {
            setTimeout(() => formatter.end(), 0);
        }
        return formatter;
    }
    createWriteStream(options) {
        const worksheet = this.workbook.addWorksheet(options?.sheetName);
        const dateFormats = options?.dateFormats ?? DEFAULT_DATE_FORMATS;
        const map = options?.map ||
            createDefaultValueMapper(dateFormats, {
                decimalSeparator: options?.valueMapperOptions?.decimalSeparator
            });
        const parser = new csv_stream_1.CsvParserStream(options?.parserOptions);
        parser.on("data", (row) => worksheet.addRow(row.map(map)));
        return parser;
    }
    // ---------------------------------------------------------------------------
    // File Operations (Browser stubs - overridden in Node.js)
    // ---------------------------------------------------------------------------
    async readFile(_filename, _options) {
        throw new Error("csv.readFile() is not available in browser.\n" +
            "Use csv.load(csvString) or csv.read(stream) instead.\n" +
            "Example: const response = await fetch('/data.csv');\n" +
            "         workbook.csv.load(await response.text());");
    }
    async writeFile(_filename, _options) {
        throw new Error("csv.writeFile() is not available in browser.\n" +
            "Use csv.writeBuffer() and trigger a download instead.\n" +
            "Example: const buffer = await workbook.csv.writeBuffer();\n" +
            "         download(new Blob([buffer]), 'output.csv');");
    }
}
exports.CSV = CSV;
// =============================================================================
// Standalone Functions (for backward compatibility)
// =============================================================================
function parseCsvToWorksheet(content, workbook, options) {
    const csv = new CSV(workbook);
    return csv.load(content, options);
}
function formatWorksheetToCsv(worksheet, options) {
    if (!worksheet) {
        return "";
    }
    const csv = new CSV(worksheet.workbook);
    return csv.writeString({ ...options, sheetId: worksheet.id });
}
var csv_stream_2 = require("./csv-stream.js");
Object.defineProperty(exports, "CsvParserStream", { enumerable: true, get: function () { return csv_stream_2.CsvParserStream; } });
Object.defineProperty(exports, "CsvFormatterStream", { enumerable: true, get: function () { return csv_stream_2.CsvFormatterStream; } });
var csv_core_2 = require("./csv-core.js");
Object.defineProperty(exports, "parseCsv", { enumerable: true, get: function () { return csv_core_2.parseCsv; } });
Object.defineProperty(exports, "formatCsv", { enumerable: true, get: function () { return csv_core_2.formatCsv; } });
