"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUserId = getUserId;
exports.getUserEmail = getUserEmail;
exports.setUserEmail = setUserEmail;
exports.getAuthor = getAuthor;
exports.isLoggedIntoCloud = isLoggedIntoCloud;
exports.checkEmailStatus = checkEmailStatus;
exports.promptForEmailUnverified = promptForEmailUnverified;
exports.checkEmailStatusOrExit = checkEmailStatusOrExit;
const input_1 = __importDefault(require("@inquirer/input"));
const chalk_1 = __importDefault(require("chalk"));
const crypto_1 = require("crypto");
const zod_1 = require("zod");
const constants_1 = require("../constants");
const envars_1 = require("../envars");
const fetch_1 = require("../fetch");
const logger_1 = __importDefault(require("../logger"));
const globalConfig_1 = require("./globalConfig");
function getUserId() {
    let globalConfig = (0, globalConfig_1.readGlobalConfig)();
    if (!globalConfig?.id) {
        const newId = (0, crypto_1.randomUUID)();
        globalConfig = { ...globalConfig, id: newId };
        (0, globalConfig_1.writeGlobalConfig)(globalConfig);
        return newId;
    }
    return globalConfig.id;
}
function getUserEmail() {
    const globalConfig = (0, globalConfig_1.readGlobalConfig)();
    return globalConfig?.account?.email || null;
}
function setUserEmail(email) {
    const config = { account: { email } };
    (0, globalConfig_1.writeGlobalConfigPartial)(config);
}
function getAuthor() {
    return (0, envars_1.getEnvString)('PROMPTFOO_AUTHOR') || getUserEmail() || null;
}
function isLoggedIntoCloud() {
    const userEmail = getUserEmail();
    return !!userEmail && !(0, envars_1.isCI)();
}
/**
 * Shared function to check email status with the promptfoo API
 * Used by both CLI and server routes
 */
async function checkEmailStatus() {
    const userEmail = (0, envars_1.isCI)() ? 'ci-placeholder@promptfoo.dev' : getUserEmail();
    if (!userEmail) {
        return {
            status: 'no_email',
            hasEmail: false,
            message: 'Redteam evals require email verification. Please enter your work email:',
        };
    }
    try {
        const resp = await (0, fetch_1.fetchWithTimeout)(`https://api.promptfoo.app/api/users/status?email=${encodeURIComponent(userEmail)}`, undefined, 500);
        const data = (await resp.json());
        return {
            status: data.status,
            message: data.message,
            email: userEmail,
            hasEmail: true,
        };
    }
    catch (e) {
        logger_1.default.debug(`Failed to check user status: ${e}`);
        // If we can't check status, assume it's OK but log the issue
        return {
            status: 'ok',
            message: 'Unable to verify email status, but proceeding',
            email: userEmail,
            hasEmail: true,
        };
    }
}
async function promptForEmailUnverified() {
    const { default: telemetry } = await Promise.resolve().then(() => __importStar(require('../telemetry')));
    let email = (0, envars_1.isCI)() ? 'ci-placeholder@promptfoo.dev' : getUserEmail();
    if (!email) {
        await telemetry.record('feature_used', {
            feature: 'promptForEmailUnverified',
        });
        const emailSchema = zod_1.z.string().email('Please enter a valid email address');
        email = await (0, input_1.default)({
            message: 'Redteam evals require email verification. Please enter your work email:',
            validate: (input) => {
                const result = emailSchema.safeParse(input);
                return result.success || result.error.errors[0].message;
            },
        });
        setUserEmail(email);
        await telemetry.record('feature_used', {
            feature: 'userCompletedPromptForEmailUnverified',
        });
    }
    await telemetry.saveConsent(email, {
        source: 'promptForEmailUnverified',
    });
}
async function checkEmailStatusOrExit() {
    const result = await checkEmailStatus();
    if (result.status === 'exceeded_limit') {
        logger_1.default.error('You have exceeded the maximum cloud inference limit. Please contact inquiries@promptfoo.dev to upgrade your account.');
        process.exit(1);
    }
    if (result.status === 'show_usage_warning' && result.message) {
        const border = '='.repeat(constants_1.TERMINAL_MAX_WIDTH);
        logger_1.default.info(chalk_1.default.yellow(border));
        logger_1.default.warn(chalk_1.default.yellow(result.message));
        logger_1.default.info(chalk_1.default.yellow(border));
    }
}
//# sourceMappingURL=accounts.js.map