"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.invokeCustomProvider = void 0;
const logger_1 = __importDefault(require("../../../logger"));
const azureSessions_1 = require("../../../util/azureSessions");
const zipBundleDirectory_1 = require("../../../util/azureSessions/zipBundleDirectory");
const invokeCustomProvider = async (req, res) => {
    try {
        if (!(0, azureSessions_1.isAzureSessionsConfigured)()) {
            res.status(503).json({
                success: false,
                message: 'Azure code interpreter is not configured. Set AZURE_SESSIONS_SUBSCRIPTION_ID, AZURE_SESSIONS_RESOURCE_GROUP, AZURE_SESSIONS_REGION, AZURE_SESSIONS_PYTHON_POOL_NAME, and AZURE_SESSIONS_NODE_POOL_NAME.',
            });
            return;
        }
        const body = req.body;
        const prompt = typeof body.prompt === 'string' ? body.prompt : '';
        if (!prompt.trim()) {
            res.status(400).json({ success: false, message: 'prompt is required' });
            return;
        }
        const language = (0, azureSessions_1.normalizeAzureSessionLanguage)(body.language ?? '');
        if (!language) {
            res.status(400).json({
                success: false,
                message: 'language must be "py" or "js" (also accepts python, javascript, node)',
            });
            return;
        }
        const env = body.env && typeof body.env === 'object' && !Array.isArray(body.env)
            ? Object.fromEntries(Object.entries(body.env).map(([key, value]) => [key, String(value ?? '')]))
            : undefined;
        const bundleDirectory = typeof body.bundleDirectory === 'string' && body.bundleDirectory.trim()
            ? body.bundleDirectory.trim()
            : (0, azureSessions_1.getDefaultExampleBundleDirectory)(language);
        const rawPath = typeof body.providerFilePath === 'string' && body.providerFilePath.trim()
            ? body.providerFilePath
            : typeof body.callApiPath === 'string' && body.callApiPath.trim()
                ? body.callApiPath
                : undefined;
        const providerFilePath = (0, azureSessions_1.resolveProviderFilePath)(language, rawPath);
        const bundleZipBuffer = (0, zipBundleDirectory_1.zipBundleDirectoryToBuffer)(bundleDirectory);
        const result = await (0, azureSessions_1.runCustomProviderInAzureSession)({
            language,
            prompt,
            env,
            bundleDirectory,
            bundleZipBuffer,
            providerFilePath,
            context: body.context,
            cleanupSession: true,
        });
        if (result.providerResponse.error) {
            res.status(502).json({
                success: false,
                message: result.providerResponse.error,
                sessionIdentifier: result.sessionIdentifier,
                stderr: result.rawExecution?.stderr,
                stdout: result.rawExecution?.stdout,
            });
            return;
        }
        res.json({
            success: true,
            sessionIdentifier: result.sessionIdentifier,
            output: result.providerResponse.output,
            tokenUsage: result.providerResponse.tokenUsage,
            cost: result.providerResponse.cost,
            metadata: result.providerResponse.metadata,
            executionTimeInMilliseconds: result.rawExecution?.executionTimeInMilliseconds,
            providerFilePath,
            callApiFunction: (0, azureSessions_1.getCallApiFunctionName)(language),
        });
    }
    catch (error) {
        logger_1.default.error(`invokeCustomProvider failed: ${error instanceof Error ? error.message : String(error)}`);
        res.status(500).json({
            success: false,
            message: error instanceof Error ? error.message : 'Failed to invoke custom provider',
        });
    }
};
exports.invokeCustomProvider = invokeCustomProvider;
//# sourceMappingURL=invoke-custom-provider.js.map