"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeAzureSessionLanguage = normalizeAzureSessionLanguage;
exports.runCustomProviderInAzureSession = runCustomProviderInAzureSession;
const node_crypto_1 = require("node:crypto");
const logger_1 = __importDefault(require("../../logger"));
const client_1 = require("./client");
const config_1 = require("./config");
const parseProviderFilePath_1 = require("./parseProviderFilePath");
const buildBootstrap_1 = require("./buildBootstrap");
const parseExecutionResult_1 = require("./parseExecutionResult");
const buildBootstrap_2 = require("./buildBootstrap");
const sessionExecutionLock_1 = require("./sessionExecutionLock");
const testRunSession_1 = require("./testRunSession");
function normalizeAzureSessionLanguage(language) {
    const value = language.trim().toLowerCase();
    if (value === 'py' || value === 'python') {
        return 'py';
    }
    if (value === 'js' || value === 'javascript' || value === 'node' || value === 'nodejs') {
        return 'js';
    }
    return null;
}
function assertExecutionSucceeded(response) {
    const status = (response.status ?? response.result?.status ?? '').toLowerCase();
    if (status && status !== 'success' && status !== 'succeeded') {
        const stderr = response.result?.stderr?.trim();
        const stdout = response.result?.stdout?.trim();
        const apiMessage = response.error?.message?.trim();
        throw new Error(stderr || apiMessage || stdout || status);
    }
}
async function runAzureSessionSteps(params) {
    const sessionIdentifier = params.sessionIdentifier ?? `trusys-${(0, node_crypto_1.randomUUID)()}`;
    const cleanupSession = params.cleanupSession ?? true;
    if (!params.bundleZipBuffer?.length) {
        throw new Error('Azure Sessions custom provider requires bundleZipBuffer (upload zip to session; do not expand on server).');
    }
    const providerFilePath = (0, parseProviderFilePath_1.resolveProviderFilePath)(params.language, params.providerFilePath);
    const client = new client_1.AzureSessionsClient(params.language, sessionIdentifier);
    logger_1.default.info(`Azure Sessions: starting custom provider run language=${params.language} session=${sessionIdentifier}`);
    try {
        const reuseSessionId = params.sessionIdentifier;
        const skipJavaScriptSetup = params.language === 'js' &&
            reuseSessionId !== undefined &&
            (0, testRunSession_1.isSessionJsBootstrapWarm)(reuseSessionId);
        if (skipJavaScriptSetup) {
            logger_1.default.info(`Azure Sessions: skipping bundle upload (warm JS session) session=${sessionIdentifier}`);
        }
        else {
            await client.uploadFile(buildBootstrap_2.TRUSYS_BUNDLE_ZIP_NAME, params.bundleZipBuffer);
            logger_1.default.info(`Azure Sessions: uploaded bundle zip (${params.bundleZipBuffer.length} bytes) session=${sessionIdentifier}`);
        }
        const executionTimeoutSeconds = (0, config_1.clampExecutionTimeoutSeconds)(params.timeoutInSeconds);
        const bootstrap = (0, buildBootstrap_1.buildBootstrapCode)(params.language, providerFilePath, {
            prompt: params.prompt,
            context: params.context ?? { vars: {} },
            env: params.env ?? {},
        }, params.language === 'js' ? { skipSetup: skipJavaScriptSetup } : undefined);
        logger_1.default.info(`Azure Sessions: executing provider session=${sessionIdentifier} timeoutSeconds=${executionTimeoutSeconds}`);
        const executionResponse = await client.executeCode(bootstrap, {
            timeoutInSeconds: executionTimeoutSeconds,
        });
        const executionMs = executionResponse.result?.executionTimeInMilliseconds;
        if (executionMs != null) {
            logger_1.default.info(`Azure Sessions: execution finished in ${executionMs}ms session=${sessionIdentifier} skipSetup=${skipJavaScriptSetup}`);
        }
        assertExecutionSucceeded(executionResponse);
        if (params.language === 'js' && reuseSessionId !== undefined && !skipJavaScriptSetup) {
            (0, testRunSession_1.markSessionJsBootstrapWarm)(reuseSessionId);
        }
        const rawExecution = {
            ...executionResponse.result,
            status: executionResponse.status ?? executionResponse.result?.status,
        };
        const providerResponse = (0, parseExecutionResult_1.parseProviderResponseFromExecution)(rawExecution);
        if (providerResponse.error) {
            logger_1.default.warn(`Azure Sessions provider error session=${sessionIdentifier}: ${providerResponse.error}`);
        }
        return {
            sessionIdentifier,
            providerResponse,
            rawExecution,
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        logger_1.default.error(`runCustomProviderInAzureSession failed: ${message}`);
        throw error;
    }
    finally {
        if (cleanupSession && process.env.TRUSYS_AZURE_SESSIONS_SKIP_CLEANUP !== '1') {
            try {
                await client.deleteSession();
            }
            catch (deleteError) {
                logger_1.default.warn(`Azure Sessions: failed to delete session ${sessionIdentifier}: ${deleteError}`);
            }
        }
    }
}
/**
 * Run a custom provider bundle in an Azure Container Apps code interpreter session.
 * Reusable from functional evaluation (RemoteCustomProvider) and sandbox APIs.
 */
async function runCustomProviderInAzureSession(params) {
    if (!(0, config_1.isAzureSessionsConfigured)()) {
        throw new Error('Azure Sessions is not configured. Set AZURE_SESSIONS_* environment variables on the server.');
    }
    const sessionIdentifier = params.sessionIdentifier ?? `trusys-${(0, node_crypto_1.randomUUID)()}`;
    if (params.sessionIdentifier) {
        return (0, sessionExecutionLock_1.withAzureSessionExecutionLock)(sessionIdentifier, () => runAzureSessionSteps(params));
    }
    return runAzureSessionSteps(params);
}
//# sourceMappingURL=runCustomProvider.js.map