"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractLinkedColumnNamesForDatasetFromTurns = extractLinkedColumnNamesForDatasetFromTurns;
const RAW_DATASET_COLUMN_REGEX = /\{\{([^}/]+)\/([^}]+)\}\}/g;
function normalizeDatasetNameKey(name) {
    return String(name || '')
        .trim()
        .toLowerCase();
}
function collectRawPromptLinkedColumns(turns, acceptedNormalizedNames) {
    const ordered = [];
    const seen = new Set();
    if (!Array.isArray(turns) || acceptedNormalizedNames.size === 0) {
        return ordered;
    }
    for (const turn of turns) {
        const allActions = [...(turn.actionsAbove || []), ...(turn.actionsBelow || [])];
        for (const action of allActions) {
            const raw = action?.rawPrompt;
            if (typeof raw !== 'string' || !raw.trim()) {
                continue;
            }
            RAW_DATASET_COLUMN_REGEX.lastIndex = 0;
            let m;
            while ((m = RAW_DATASET_COLUMN_REGEX.exec(raw)) !== null) {
                const dsName = normalizeDatasetNameKey(m[1]);
                const col = String(m[2] || '').trim();
                if (!col || !acceptedNormalizedNames.has(dsName)) {
                    continue;
                }
                if (!seen.has(col)) {
                    seen.add(col);
                    ordered.push(col);
                }
            }
        }
    }
    return ordered;
}
/**
 * Distinct column names on conversation-builder **turns** for `targetDatasetId`:
 * - `userResponse` actions with `datasetId` + `columnName`
 * - `{{datasetName/columnName}}` in `rawPrompt` when `datasetNames` matches the dataset name (case-insensitive)
 */
function extractLinkedColumnNamesForDatasetFromTurns(turns, targetDatasetId, options) {
    if (!Array.isArray(turns) || !targetDatasetId) {
        return [];
    }
    const ordered = [];
    const seen = new Set();
    for (const turn of turns) {
        const allActions = [...(turn.actionsAbove || []), ...(turn.actionsBelow || [])];
        for (const action of allActions) {
            if (String(action?.datasetId || '') !== String(targetDatasetId)) {
                continue;
            }
            const col = action?.columnName;
            if (typeof col !== 'string' || !col.trim()) {
                continue;
            }
            const c = col.trim();
            if (!seen.has(c)) {
                seen.add(c);
                ordered.push(c);
            }
        }
    }
    const acceptedNames = new Set((options?.datasetNames ?? [])
        .map((n) => normalizeDatasetNameKey(String(n)))
        .filter((n) => n.length > 0));
    for (const c of collectRawPromptLinkedColumns(turns, acceptedNames)) {
        if (!seen.has(c)) {
            seen.add(c);
            ordered.push(c);
        }
    }
    return ordered;
}
//# sourceMappingURL=conversationBuilderTurnsDatasetColumns.js.map