import { C as isCI, b as getEnvString, i as logger_default } from "./logger-BudIH0qK.js";
import { d as writeGlobalConfigPartial, l as readGlobalConfig, r as fetchWithTimeout, s as CloudConfig, u as writeGlobalConfig, w as TERMINAL_MAX_WIDTH } from "./fetch-D70iPJNm.js";
import chalk from "chalk";
import { z } from "zod";
import input from "@inquirer/input";

//#region src/types/email.ts
const EMAIL_OK_STATUS = "ok";
const BAD_EMAIL_RESULT = "bad_email";
const EmailValidationStatus = {
	OK: EMAIL_OK_STATUS,
	EXCEEDED_LIMIT: "exceeded_limit",
	SHOW_USAGE_WARNING: "show_usage_warning",
	RISKY_EMAIL: "risky_email",
	DISPOSABLE_EMAIL: "disposable_email"
};
const NO_EMAIL_STATUS = "no_email";

//#endregion
//#region src/globalConfig/accounts.ts
function getUserId() {
	let globalConfig = readGlobalConfig();
	if (!globalConfig?.id) {
		const newId = crypto.randomUUID();
		globalConfig = {
			...globalConfig,
			id: newId
		};
		writeGlobalConfig(globalConfig);
		return newId;
	}
	return globalConfig.id;
}
function getUserEmail() {
	return readGlobalConfig()?.account?.email || null;
}
function setUserEmail(email) {
	const account = readGlobalConfig()?.account ?? {};
	account.email = email;
	writeGlobalConfigPartial({ account });
}
function getUserEmailNeedsValidation() {
	return readGlobalConfig()?.account?.emailNeedsValidation || false;
}
function setUserEmailNeedsValidation(needsValidation) {
	const account = readGlobalConfig()?.account ?? {};
	account.emailNeedsValidation = needsValidation;
	writeGlobalConfigPartial({ account });
}
function getUserEmailValidated() {
	return readGlobalConfig()?.account?.emailValidated || false;
}
function setUserEmailValidated(validated) {
	const account = readGlobalConfig()?.account ?? {};
	account.emailValidated = validated;
	writeGlobalConfigPartial({ account });
}
function getAuthor() {
	return getEnvString("PROMPTFOO_AUTHOR") || getUserEmail() || null;
}
function isLoggedIntoCloud() {
	return new CloudConfig().isEnabled();
}
/**
* Get the authentication method used for cloud access
* @returns 'api-key' | 'email' | 'none'
*/
function getAuthMethod() {
	const hasApiKey = new CloudConfig().isEnabled();
	const hasEmail = !!getUserEmail();
	if (hasApiKey && hasEmail) return "api-key";
	if (hasApiKey) return "api-key";
	if (hasEmail) return "email";
	return "none";
}
/**
* Shared function to check email status with the promptfoo API
* Used by both CLI and server routes
*/
async function checkEmailStatus(options) {
	const { default: telemetry } = await import("./telemetry-e0-B3nMm.js");
	const userEmail = isCI() ? "ci-placeholder@promptfoo.dev" : getUserEmail();
	if (!userEmail) return {
		status: NO_EMAIL_STATUS,
		hasEmail: false,
		message: "Redteam evals require email verification. Please enter your work email:"
	};
	try {
		const validateParam = options?.validate ? "&validate=true" : "";
		const timeout = options?.validate ? 3e3 : 500;
		if (options?.validate) logger_default.info(`Checking email...`);
		const data = await (await fetchWithTimeout(`${getEnvString("PROMPTFOO_CLOUD_API_URL", "https://api.promptfoo.app")}/api/users/status?email=${encodeURIComponent(userEmail)}${validateParam}`, void 0, timeout)).json();
		if (options?.validate) if (new Set([EmailValidationStatus.RISKY_EMAIL, EmailValidationStatus.DISPOSABLE_EMAIL]).has(data.status)) await telemetry.saveConsent(userEmail, { source: "filteredInvalidEmail" });
		else {
			setUserEmailValidated(true);
			await telemetry.saveConsent(userEmail, { source: "promptForEmailValidated" });
		}
		return {
			status: data.status,
			message: data.message,
			email: userEmail,
			hasEmail: true
		};
	} catch (e) {
		logger_default.debug(`Failed to check user status: ${e}`);
		return {
			status: EmailValidationStatus.OK,
			message: "Unable to verify email status, but proceeding",
			email: userEmail,
			hasEmail: true
		};
	}
}
async function promptForEmailUnverified() {
	const { default: telemetry } = await import("./telemetry-e0-B3nMm.js");
	const existingEmail = getUserEmail();
	let email = isCI() ? "ci-placeholder@promptfoo.dev" : existingEmail;
	const existingEmailNeedsValidation = !isCI() && getUserEmailNeedsValidation();
	const existingEmailValidated = isCI() || getUserEmailValidated();
	let emailNeedsValidation = existingEmailNeedsValidation && !existingEmailValidated;
	if (!email) {
		await telemetry.record("feature_used", { feature: "promptForEmailUnverified" });
		const emailSchema = z.email();
		try {
			email = await input({
				message: "Redteam evals require email verification. Please enter your work email:",
				validate: (input$1) => {
					const result = emailSchema.safeParse(input$1);
					return result.success || result.error.issues[0].message;
				}
			});
		} catch (error) {
			const err = error;
			if (err?.name === "AbortPromptError" || err?.name === "ExitPromptError") process.exit(1);
			logger_default.error(`failed to prompt for email: ${err}`);
			throw err;
		}
		setUserEmail(email);
		setUserEmailNeedsValidation(true);
		setUserEmailValidated(false);
		emailNeedsValidation = true;
		await telemetry.record("feature_used", { feature: "userCompletedPromptForEmailUnverified" });
	}
	return { emailNeedsValidation };
}
async function checkEmailStatusAndMaybeExit(options) {
	const result = await checkEmailStatus(options);
	if (result.status === EmailValidationStatus.RISKY_EMAIL || result.status === EmailValidationStatus.DISPOSABLE_EMAIL) {
		logger_default.error("Please use a valid work email.");
		setUserEmail("");
		return BAD_EMAIL_RESULT;
	}
	if (result.status === EmailValidationStatus.EXCEEDED_LIMIT) {
		logger_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 === EmailValidationStatus.SHOW_USAGE_WARNING && result.message) {
		const border = "=".repeat(TERMINAL_MAX_WIDTH);
		logger_default.info(chalk.yellow(border));
		logger_default.warn(chalk.yellow(result.message));
		logger_default.info(chalk.yellow(border));
	}
	return EMAIL_OK_STATUS;
}

//#endregion
export { getUserId as a, setUserEmail as c, getUserEmail as i, EMAIL_OK_STATUS as l, getAuthMethod as n, isLoggedIntoCloud as o, getAuthor as r, promptForEmailUnverified as s, checkEmailStatusAndMaybeExit as t };
//# sourceMappingURL=accounts-DGRucLWV.js.map