"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.providersIncludeAzureSessionsCustomAI = providersIncludeAzureSessionsCustomAI;
exports.downloadCustomAIBundleZip = downloadCustomAIBundleZip;
exports.clearSessionPrepareInFlight = clearSessionPrepareInFlight;
exports.ensureAzureSessionBundlePrepared = ensureAzureSessionBundlePrepared;
exports.prepareAzureSessionsForTestRunProviders = prepareAzureSessionsForTestRunProviders;
const buildProviderForEval_1 = require("../customAIApplication/buildProviderForEval");
const validateCustomAIBundle_1 = require("../customAIApplication/validateCustomAIBundle");
const fetchBlobFilesFromAzure_1 = require("../fetchBlobFilesFromAzure");
const runCustomProvider_1 = require("./runCustomProvider");
const testRunSession_1 = require("./testRunSession");
const prepareInFlight = new Map();
function providersIncludeAzureSessionsCustomAI(providers) {
    if (!Array.isArray(providers)) {
        return false;
    }
    return providers.some((provider) => provider &&
        typeof provider === 'object' &&
        provider.id === buildProviderForEval_1.AZURE_SESSIONS_CUSTOM_AI_PROVIDER_ID);
}
async function downloadCustomAIBundleZip(bundleBlobUrl, accessToken, apiKey) {
    const downloadUrl = await (0, fetchBlobFilesFromAzure_1.resolvePrivateBlobDownloadUrl)(bundleBlobUrl, accessToken, apiKey);
    const response = await fetch(decodeURIComponent(downloadUrl));
    if (!response.ok) {
        throw new Error(`Failed to download bundle zip: HTTP ${response.status}`);
    }
    return Buffer.from(await response.arrayBuffer());
}
function normalizeProviderPathInZip(applicationPath) {
    return (0, validateCustomAIBundle_1.normalizeZipEntryPath)(applicationPath.replace(/\\/g, '/'));
}
function clearSessionPrepareInFlight(sessionIdentifier) {
    prepareInFlight.delete(sessionIdentifier);
}
async function ensureAzureSessionBundlePrepared(params) {
    const sessionIdentifier = (0, testRunSession_1.buildAzureSessionIdentifierForTestRun)(params.testRunId, params.applicationId);
    const cachedPath = (0, testRunSession_1.getPreparedSessionProviderFilePath)(sessionIdentifier);
    if ((0, testRunSession_1.isSessionBundlePrepared)(sessionIdentifier) && cachedPath) {
        return cachedPath;
    }
    const inFlight = prepareInFlight.get(sessionIdentifier);
    if (inFlight) {
        return inFlight;
    }
    const promise = (async () => {
        const zipBuffer = await downloadCustomAIBundleZip(params.bundleBlobUrl, params.accessToken, params.apiKey);
        (0, testRunSession_1.cacheSessionBundleZip)(sessionIdentifier, zipBuffer);
        const providerFilePath = normalizeProviderPathInZip(params.applicationPath);
        (0, testRunSession_1.markSessionBundlePrepared)(params.testRunId, sessionIdentifier, providerFilePath);
        return providerFilePath;
    })();
    prepareInFlight.set(sessionIdentifier, promise);
    try {
        return await promise;
    }
    finally {
        prepareInFlight.delete(sessionIdentifier);
    }
}
async function prepareAzureSessionsForTestRunProviders(providers, accessToken, testRunId) {
    if (!Array.isArray(providers)) {
        return;
    }
    await Promise.all(providers.map(async (provider) => {
        if (!provider || typeof provider !== 'object') {
            return;
        }
        const record = provider;
        if (record.id !== buildProviderForEval_1.AZURE_SESSIONS_CUSTOM_AI_PROVIDER_ID) {
            return;
        }
        const config = record.config;
        if (!config?.applicationId || !config.bundleBlobUrl || !config.applicationPath || !config.language) {
            return;
        }
        if (!(0, runCustomProvider_1.normalizeAzureSessionLanguage)(config.language)) {
            return;
        }
        await ensureAzureSessionBundlePrepared({
            accessToken,
            testRunId,
            applicationId: config.applicationId,
            bundleBlobUrl: config.bundleBlobUrl,
            applicationPath: config.applicationPath,
            language: config.language,
        });
    }));
}
//# sourceMappingURL=prepareSessionBundle.js.map