const ENABLED_VALUES = new Set(["1", "true", "yes", "on"]);
const DISABLED_VALUES = new Set(["0", "false", "no", "off"]);

const normalizeFlagValue = (value?: string) => value?.trim().toLowerCase();

export const isAiFlagEnabled = (value?: string): boolean => {
	const normalizedValue = normalizeFlagValue(value);
	if (!normalizedValue) {
		return true;
	}

	if (ENABLED_VALUES.has(normalizedValue)) {
		return true;
	}

	if (DISABLED_VALUES.has(normalizedValue)) {
		return false;
	}

	return true;
};

export const isAdminAiEnabled = (
	env: Record<string, string | undefined> = process.env,
) => isAiFlagEnabled(env.AI_ENABLED);

export const isClientAiEnabled = (
	env: Record<string, string | undefined> = process.env,
) => isAiFlagEnabled(env.NEXT_PUBLIC_AI_ENABLED ?? env.AI_ENABLED);

export const getAiDisabledMessage = () =>
	"AI integrations are currently disabled by the administrator.";
