import path from 'path';
import fs from 'fs';
import { AgentFunctionBase } from './utils/index.js';
import { AgentOutputType, ChatMessageBuilder } from '../agent-core/index.js';
function detectDelimiter(row) {
    const supportedDelimiters = [',', ';', '\t', '|', ':'];
    for (const delimiter of supportedDelimiters) {
        if (row.includes(delimiter)) {
            return delimiter;
        }
    }
    return supportedDelimiters[0];
}
function parseCSV(data) {
    if (data.indexOf('\n') === -1 && path.extname(data) === '.csv') {
        data = fs.readFileSync(data, 'utf-8');
    }
    const rows = data.trim().split('\n');
    const delimiter = detectDelimiter(rows[0]);
    return { rows: rows.map(row => row.split(delimiter)), delimiter };
}
function serializeCSV(rows, delimiter) {
    return rows.map(row => row.join(delimiter)).join('\n');
}
function addColumnToCSVRows(rows, column, values) {
    if (values.length + 1 !== rows.length) {
        throw new Error('Mismatch in number of rows and provided values');
    }
    rows[0].push(column);
    for (let i = 1; i < rows.length; i++) {
        rows[i].push(values[i - 1]);
    }
    return rows;
}
const addColumnToCSV = ({ csv, column, values, outputFile }) => {
    const { rows, delimiter } = parseCSV(csv);
    const updatedRows = addColumnToCSVRows(rows, column, values);
    const result = serializeCSV(updatedRows, delimiter);
    if (typeof outputFile === 'string') {
        fs.writeFileSync(outputFile, result);
    }
    return result;
};
export class CsvAddColumnFunction extends AgentFunctionBase {
    name = 'csv_addColumn';
    description = 'Adds a new column to a CSV';
    parameters = {
        type: 'object',
        properties: {
            csv: {
                type: 'string',
            },
            column: {
                type: 'string',
            },
            values: {
                type: 'array',
                items: {
                    type: 'string',
                },
            },
            outputFile: {
                type: 'string',
                description: 'Write the result to a file',
            },
        },
        required: ['csv', 'column', 'values'],
        additionalProperties: false,
    };
    buildExecutor(agent) {
        return async (params, rawParams) => {
            addColumnToCSV(params);
            return this.onSuccess(agent, params, rawParams);
        };
    }
    onSuccess(agent, params, rawParams) {
        return {
            outputs: [
                {
                    type: AgentOutputType.Success,
                    title: `Created '${params.csv}' file.`,
                    content: `Created the following script:
--------------
CSV: ${params.csv}\n
--------------
`,
                },
            ],
            messages: [
                ChatMessageBuilder.functionCall(this.name, rawParams),
                ChatMessageBuilder.functionCallResult(this.name, `Script '${params.csv}' created.`),
            ],
        };
    }
}
