"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.stripAuthFromUrl = stripAuthFromUrl;
exports.createShareableUrl = createShareableUrl;
const input_1 = __importDefault(require("@inquirer/input"));
const chalk_1 = __importDefault(require("chalk"));
const url_1 = require("url");
const constants_1 = require("./constants");
const envars_1 = require("./envars");
const fetch_1 = require("./fetch");
const accounts_1 = require("./globalConfig/accounts");
const accounts_2 = require("./globalConfig/accounts");
const cloud_1 = require("./globalConfig/cloud");
const logger_1 = __importDefault(require("./logger"));
const invariant_1 = __importDefault(require("./util/invariant"));
async function targetHostCanUseNewResults(apiHost) {
    const response = await (0, fetch_1.fetchWithProxy)(`${apiHost}/health`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        },
    });
    if (!response.ok) {
        return false;
    }
    const responseJson = await response.json();
    return 'version' in responseJson;
}
async function sendEvalResults(evalRecord, url) {
    await evalRecord.loadResults();
    const headers = {
        'Content-Type': 'application/json',
    };
    if (cloud_1.cloudConfig.isEnabled()) {
        headers['Authorization'] = `Bearer ${cloud_1.cloudConfig.getApiKey()}`;
    }
    const response = await (0, fetch_1.fetchWithProxy)(url, {
        method: 'POST',
        headers,
        body: JSON.stringify(evalRecord),
    });
    if (!response.ok) {
        throw new Error(`Failed to send eval results: ${response.statusText}`);
    }
    const evalId = (await response.json()).id;
    return evalId;
}
/**
 * Removes authentication information (username and password) from a URL.
 *
 * This function addresses a security concern raised in GitHub issue #1184,
 * where sensitive authentication information was being displayed in the CLI output.
 * By default, we now strip this information to prevent accidental exposure of credentials.
 *
 * @param urlString - The URL string that may contain authentication information.
 * @returns A new URL string with username and password removed, if present.
 *          If URL parsing fails, it returns the original string.
 */
function stripAuthFromUrl(urlString) {
    try {
        const url = new url_1.URL(urlString);
        url.username = '';
        url.password = '';
        return url.toString();
    }
    catch {
        logger_1.default.warn('Failed to parse URL, returning original');
        return urlString;
    }
}
async function createShareableUrl(evalRecord, showAuth = false) {
    if (process.stdout.isTTY && !(0, envars_1.isCI)() && !(0, envars_1.getEnvBool)('PROMPTFOO_DISABLE_SHARE_EMAIL_REQUEST')) {
        let email = (0, accounts_2.getUserEmail)();
        if (!email) {
            email = await (0, input_1.default)({
                message: `${chalk_1.default.bold('Please enter your work email address')} (for managing shared URLs):`,
                validate: (value) => {
                    return value.includes('@') || 'Please enter a valid email address';
                },
            });
            (0, accounts_2.setUserEmail)(email);
        }
        evalRecord.author = email;
        await evalRecord.save();
    }
    let response;
    let apiBaseUrl;
    let url;
    if (cloud_1.cloudConfig.isEnabled()) {
        apiBaseUrl = cloud_1.cloudConfig.getApiHost();
        url = `${apiBaseUrl}/results`;
        const loggedInEmail = (0, accounts_2.getUserEmail)();
        (0, invariant_1.default)(loggedInEmail, 'User email is not set');
        const evalAuthor = evalRecord.author;
        if (evalAuthor !== loggedInEmail) {
            logger_1.default.warn(`Warning: Changing eval author from ${evalAuthor} to logged-in user ${loggedInEmail}`);
        }
        evalRecord.author = loggedInEmail;
        await evalRecord.save();
    }
    else {
        apiBaseUrl =
            typeof evalRecord.config.sharing === 'object'
                ? evalRecord.config.sharing.apiBaseUrl || constants_1.SHARE_API_BASE_URL
                : constants_1.SHARE_API_BASE_URL;
        url = `${apiBaseUrl}/api/eval`;
    }
    const canUseNewResults = cloud_1.cloudConfig.isEnabled() || (await targetHostCanUseNewResults(apiBaseUrl));
    logger_1.default.debug(`Sharing with ${url} canUseNewResults: ${canUseNewResults} Use old results: ${evalRecord.useOldResults()}`);
    let evalId;
    if (canUseNewResults && !evalRecord.useOldResults()) {
        evalId = await sendEvalResults(evalRecord, url);
    }
    else {
        const summary = await evalRecord.toEvaluateSummary();
        const table = await evalRecord.getTable();
        const v2Summary = {
            ...summary,
            table,
            version: 2,
        };
        logger_1.default.debug(`Sending eval results (v2 result file) to ${url}`);
        // check if we're using the cloud
        const sharedResults = {
            data: {
                version: 3,
                createdAt: new Date().toISOString(),
                author: (0, accounts_1.getAuthor)(),
                results: v2Summary,
                config: evalRecord.config,
            },
        };
        if (cloud_1.cloudConfig.isEnabled()) {
            response = await (0, fetch_1.fetchWithProxy)(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${cloud_1.cloudConfig.getApiKey()}`,
                },
                body: JSON.stringify(sharedResults),
            });
        }
        else {
            response = await (0, fetch_1.fetchWithProxy)(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(sharedResults),
            });
        }
        if (!response.ok) {
            logger_1.default.error(`Failed to create shareable URL: ${response.statusText}`);
            return null;
        }
        const responseJson = (await response.json());
        if (responseJson.error) {
            logger_1.default.error(`Failed to create shareable URL: ${responseJson.error}`);
            return null;
        }
        evalId = responseJson.id;
    }
    logger_1.default.debug(`New eval ID on remote instance: ${evalId}`);
    let appBaseUrl = constants_1.SHARE_VIEW_BASE_URL;
    let fullUrl = constants_1.SHARE_VIEW_BASE_URL;
    if (cloud_1.cloudConfig.isEnabled()) {
        appBaseUrl = cloud_1.cloudConfig.getAppUrl();
        fullUrl = `${appBaseUrl}/eval/${evalId}`;
    }
    else {
        const appBaseUrl = typeof evalRecord.config.sharing === 'object'
            ? evalRecord.config.sharing.appBaseUrl
            : constants_1.SHARE_VIEW_BASE_URL;
        fullUrl =
            constants_1.SHARE_VIEW_BASE_URL === constants_1.DEFAULT_SHARE_VIEW_BASE_URL
                ? `${appBaseUrl}/eval/${evalId}`
                : `${appBaseUrl}/eval/?evalId=${evalId}`;
    }
    return showAuth ? fullUrl : stripAuthFromUrl(fullUrl);
}
//# sourceMappingURL=share.js.map