"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AzureSessionsClient = void 0;
const auth_1 = require("./auth");
const authLogging_1 = require("./authLogging");
const config_1 = require("./config");
function azureApiErrorMessage(status, body, statusText) {
    const trimmed = body.trim();
    if (trimmed) {
        return trimmed;
    }
    if (statusText.trim()) {
        return statusText.trim();
    }
    return String(status);
}
class AzureSessionsClient {
    constructor(language, sessionIdentifier) {
        this.language = language;
        this.sessionIdentifier = sessionIdentifier;
    }
    get baseUrl() {
        return (0, config_1.getSessionPoolManagementEndpoint)(this.language);
    }
    get apiVersion() {
        return (0, config_1.getAzureSessionsConfig)()?.apiVersion ?? config_1.DEFAULT_AZURE_SESSIONS_API_VERSION;
    }
    async authHeaders() {
        const tokenInfo = await (0, auth_1.getAzureSessionsAccessTokenInfo)();
        return {
            headers: { Authorization: `Bearer ${tokenInfo.token}` },
            identityLabel: tokenInfo.identityLabel,
            credentialSource: tokenInfo.credentialSource,
        };
    }
    buildUrl(path, query = {}) {
        const params = new URLSearchParams({
            'api-version': this.apiVersion,
            identifier: this.sessionIdentifier,
            ...query,
        });
        return `${this.baseUrl}/${path}?${params.toString()}`;
    }
    async uploadFile(relativePath, content) {
        const normalized = relativePath.replace(/\\/g, '/');
        const slashIndex = normalized.lastIndexOf('/');
        const fileName = slashIndex >= 0 ? normalized.slice(slashIndex + 1) : normalized;
        const parentPath = slashIndex >= 0 ? normalized.slice(0, slashIndex) : '';
        const query = {};
        if (parentPath) {
            query.path = parentPath;
        }
        const form = new FormData();
        const blob = new Blob([new Uint8Array(content)], { type: 'application/octet-stream' });
        form.append('file', blob, fileName);
        const auth = await this.authHeaders();
        const url = this.buildUrl('files', query);
        (0, authLogging_1.logAzureSessionsAuth)('API uploadFile request', {
            language: this.language,
            session: this.sessionIdentifier,
            fileName,
            bytes: content.length,
            identity: auth.identityLabel,
        });
        const response = await fetch(url, {
            method: 'POST',
            headers: auth.headers,
            body: form,
        });
        const body = await response.text();
        if (!response.ok) {
            throw new Error(azureApiErrorMessage(response.status, body, response.statusText));
        }
    }
    parseExecutionBody(response, text) {
        if (!response.ok) {
            throw new Error(azureApiErrorMessage(response.status, text, response.statusText));
        }
        try {
            return JSON.parse(text);
        }
        catch {
            throw new Error(text.trim() || response.statusText);
        }
    }
    /**
     * Run code via synchronous POST /executions (Microsoft Learn code interpreter API).
     * @see https://learn.microsoft.com/en-us/azure/container-apps/sessions-code-interpreter
     */
    async executeCode(code, options) {
        const timeoutInSeconds = (0, config_1.clampExecutionTimeoutSeconds)(options?.timeoutInSeconds);
        const outputStreamsMaxLength = this.language === 'js'
            ? Number(process.env.AZURE_SESSIONS_JS_OUTPUT_MAX_LENGTH ?? 8192)
            : Number(process.env.AZURE_SESSIONS_OUTPUT_MAX_LENGTH ?? 65536);
        const auth = await this.authHeaders();
        const response = await fetch(this.buildUrl('executions'), {
            method: 'POST',
            headers: {
                ...auth.headers,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                codeInputType: 'Inline',
                executionType: 'Synchronous',
                code,
                timeoutInSeconds,
                outputStreamsMaxLength,
            }),
        });
        const text = await response.text();
        return this.parseExecutionBody(response, text);
    }
    async deleteSession() {
        const auth = await this.authHeaders();
        const response = await fetch(this.buildUrl('session'), {
            method: 'DELETE',
            headers: auth.headers,
        });
        if (!response.ok && response.status !== 204) {
            const body = await response.text();
            throw new Error(azureApiErrorMessage(response.status, body, response.statusText));
        }
    }
}
exports.AzureSessionsClient = AzureSessionsClient;
//# sourceMappingURL=client.js.map