"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.readPrompts = exports.processPrompt = exports.readProviderPromptMap = void 0;
const glob_1 = require("glob");
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
const logger_1 = __importDefault(require("../logger"));
const javascript_1 = require("./processors/javascript");
const json_1 = require("./processors/json");
const jsonl_1 = require("./processors/jsonl");
const python_1 = require("./processors/python");
const string_1 = require("./processors/string");
const text_1 = require("./processors/text");
const yaml_1 = require("./processors/yaml");
const utils_1 = require("./utils");
__exportStar(require("./grading"), exports);
/**
 * Reads and maps provider prompts based on the configuration and parsed prompts.
 * @param config - The configuration object.
 * @param parsedPrompts - Array of parsed prompts.
 * @returns A map of provider IDs to their respective prompts.
 */
function readProviderPromptMap(config, parsedPrompts) {
    const ret = {};
    if (!config.providers) {
        return ret;
    }
    const allPrompts = [];
    for (const prompt of parsedPrompts) {
        allPrompts.push(prompt.label);
    }
    if (typeof config.providers === 'string') {
        return { [config.providers]: allPrompts };
    }
    if (typeof config.providers === 'function') {
        return { 'Custom function': allPrompts };
    }
    for (const provider of config.providers) {
        if (typeof provider === 'object') {
            // It's either a ProviderOptionsMap or a ProviderOptions
            if (provider.id) {
                const rawProvider = provider;
                (0, tiny_invariant_1.default)(rawProvider.id, 'You must specify an `id` on the Provider when you override options.prompts');
                ret[rawProvider.id] = rawProvider.prompts || allPrompts;
                if (rawProvider.label) {
                    ret[rawProvider.label] = rawProvider.prompts || allPrompts;
                }
            }
            else {
                const rawProvider = provider;
                const originalId = Object.keys(rawProvider)[0];
                const providerObject = rawProvider[originalId];
                const id = providerObject.id || originalId;
                ret[id] = rawProvider[originalId].prompts || allPrompts;
            }
        }
    }
    return ret;
}
exports.readProviderPromptMap = readProviderPromptMap;
/**
 * Processes a raw prompt based on its content type and path.
 * @param prompt - The raw prompt data.
 * @param basePath - Base path for file resolution.
 * @param maxRecursionDepth - Maximum recursion depth for globbing.
 * @returns Promise resolving to an array of processed prompts.
 */
async function processPrompt(prompt, basePath = '', maxRecursionDepth = 1) {
    (0, tiny_invariant_1.default)(typeof prompt.raw === 'string', `prompt.raw must be a string, but got ${JSON.stringify(prompt.raw)}`);
    if (!(0, utils_1.maybeFilePath)(prompt.raw)) {
        return (0, string_1.processString)(prompt);
    }
    const { extension, functionName, isPathPattern, promptPath, } = (0, utils_1.parsePathOrGlob)(basePath, prompt.raw);
    if (isPathPattern && maxRecursionDepth > 0) {
        const globbedPath = (0, glob_1.globSync)(promptPath.replace(/\\/g, '/'), {
            windowsPathsNoEscape: true,
        });
        logger_1.default.debug(`Expanded prompt ${prompt.raw} to ${promptPath} and then to ${JSON.stringify(globbedPath)}`);
        const prompts = [];
        for (const globbedFilePath of globbedPath) {
            const processedPrompts = await processPrompt({ raw: globbedFilePath }, basePath, maxRecursionDepth - 1);
            prompts.push(...processedPrompts);
        }
        return prompts;
    }
    if (extension === '.json') {
        return (0, json_1.processJsonFile)(promptPath, prompt);
    }
    if (extension === '.jsonl') {
        return (0, jsonl_1.processJsonlFile)(promptPath, prompt);
    }
    if (['.js', '.cjs', '.mjs'].includes(extension)) {
        return (0, javascript_1.processJsFile)(promptPath, prompt, functionName);
    }
    if (extension === '.py') {
        return (0, python_1.processPythonFile)(promptPath, prompt, functionName);
    }
    if (extension === '.txt') {
        return (0, text_1.processTxtFile)(promptPath, prompt);
    }
    if (['.yml', '.yaml'].includes(extension)) {
        return (0, yaml_1.processYamlFile)(promptPath, prompt);
    }
    return [];
}
exports.processPrompt = processPrompt;
/**
 * Reads and processes prompts from a specified path or glob pattern.
 * @param promptPathOrGlobs - The path or glob pattern.
 * @param basePath - Base path for file resolution.
 * @returns Promise resolving to an array of processed prompts.
 */
async function readPrompts(promptPathOrGlobs, basePath = '') {
    logger_1.default.debug(`Reading prompts from ${JSON.stringify(promptPathOrGlobs)}`);
    const promptPartials = (0, utils_1.normalizeInput)(promptPathOrGlobs);
    const prompts = [];
    for (const prompt of promptPartials) {
        const promptBatch = await processPrompt(prompt, basePath);
        if (promptBatch.length === 0) {
            throw new Error(`There are no prompts in ${JSON.stringify(prompt.raw)}`);
        }
        prompts.push(...promptBatch);
    }
    return prompts;
}
exports.readPrompts = readPrompts;
//# sourceMappingURL=index.js.map