"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveCustomWorkerRequestParams = resolveCustomWorkerRequestParams;
exports.applyRequestParamsPayloadOverride = applyRequestParamsPayloadOverride;
const env_template_1 = require("../config/env-template");
const errors_1 = require("./errors");
function resolveCustomWorkerRequestParams(input) {
    if (input.requestParams === undefined) {
        return undefined;
    }
    return resolveTemplateJsonValue("requestParams", input.requestParams, {
        env: input.env,
    });
}
function applyRequestParamsPayloadOverride(session, requestParams) {
    if (requestParams === undefined || session.agent === undefined) {
        return;
    }
    const previousOnPayload = session.agent.onPayload;
    session.agent.onPayload = async (payload, model) => {
        const previousPayload = await previousOnPayload?.(payload, model);
        const basePayload = previousPayload === undefined ? payload : previousPayload;
        return {
            ...(isJsonObjectLike(basePayload) ? basePayload : {}),
            ...requestParams,
        };
    };
}
function resolveTemplateJsonValue(label, value, input) {
    if (typeof value === "string") {
        return resolveTemplateValue(label, value, {
            env: input.env,
            rejectEmpty: false,
        });
    }
    if (Array.isArray(value)) {
        return value.map((item, index) => resolveTemplateJsonValue(`${label}[${index}]`, item, input));
    }
    if (value !== null && typeof value === "object") {
        return Object.fromEntries(Object.entries(value).map(([key, item]) => [
            key,
            resolveTemplateJsonValue(`${label}.${key}`, item, input),
        ]));
    }
    return value;
}
function resolveTemplateValue(label, value, input) {
    let resolved;
    try {
        resolved = (0, env_template_1.resolveConfigEnvTemplate)(value, input.env);
    }
    catch (error) {
        if (error instanceof env_template_1.MissingConfigEnvTemplateValueError) {
            throw new errors_1.WorkerUnavailableError(`customWorkers.${label} references missing environment variable: ${error.envName}`);
        }
        if (error instanceof env_template_1.EmptyConfigEnvTemplateValueError) {
            throw new errors_1.WorkerUnavailableError(`customWorkers.${label} references empty environment variable: ${error.envName}`);
        }
        if (error instanceof env_template_1.InvalidConfigEnvTemplateError) {
            throw new errors_1.WorkerUnavailableError(`customWorkers.${label} has invalid environment template: ${error.expression}`);
        }
        throw error;
    }
    if (input.rejectEmpty && resolved.trim().length === 0) {
        throw new errors_1.WorkerUnavailableError(`customWorkers.${label} resolved to an empty value.`);
    }
    return resolved;
}
function isJsonObjectLike(value) {
    return value !== null && typeof value === "object" && !Array.isArray(value);
}
