"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Telemetry = exports.POSTHOG_KEY = exports.TelemetryEventSchema = void 0;
const crypto_1 = require("crypto");
const posthog_node_1 = require("posthog-node");
const zod_1 = require("zod");
const constants_1 = require("./constants");
const envars_1 = require("./envars");
const fetch_1 = require("./fetch");
const globalConfig_1 = require("./globalConfig/globalConfig");
const logger_1 = __importDefault(require("./logger"));
exports.TelemetryEventSchema = zod_1.z.object({
    event: zod_1.z.enum([
        'assertion_used',
        'command_used',
        'eval_ran',
        'feature_used',
        'funnel',
        'webui_api',
        'webui_page_view',
    ]),
    packageVersion: zod_1.z.string().optional().default(constants_1.VERSION),
    properties: zod_1.z.record(zod_1.z.union([zod_1.z.string(), zod_1.z.number(), zod_1.z.boolean(), zod_1.z.array(zod_1.z.string())])),
});
// NEVER change this to getEnvString - `replace-keys` depends on it directly referencing process.env
exports.POSTHOG_KEY = 'phc_E5n5uHnDo2eREJL1uqX1cIlbkoRby4yFWt3V94HqRRg';
const CONSENT_ENDPOINT = 'https://api.promptfoo.dev/consent';
const EVENTS_ENDPOINT = 'https://a.promptfoo.app';
const KA_ENDPOINT = 'https://ka.promptfoo.app/';
let posthogClient = null;
try {
    posthogClient = exports.POSTHOG_KEY
        ? new posthog_node_1.PostHog(exports.POSTHOG_KEY, {
            host: (0, envars_1.getEnvString)('PROMPTFOO_POSTHOG_HOST', EVENTS_ENDPOINT),
        })
        : null;
}
catch {
    posthogClient = null;
}
const TELEMETRY_TIMEOUT_MS = 1000;
class Telemetry {
    constructor() {
        this.telemetryDisabledRecorded = false;
        logger_1.default.debug(`Telemetry enabled: ${!this.disabled}`);
        const globalConfig = (0, globalConfig_1.readGlobalConfig)();
        this.id = globalConfig?.id;
        this.email = globalConfig?.account?.email;
        this.identify();
    }
    identify() {
        if (this.disabled) {
            return;
        }
        if (posthogClient && this.email) {
            posthogClient.identify({
                distinctId: this.id,
                properties: { email: this.email },
            });
        }
        fetch(KA_ENDPOINT, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ profile_id: this.id, email: this.email }),
        }).catch(() => {
            // pass
        });
    }
    get disabled() {
        return (0, envars_1.getEnvBool)('PROMPTFOO_DISABLE_TELEMETRY');
    }
    recordTelemetryDisabled() {
        if (!this.telemetryDisabledRecorded) {
            this.sendEvent('feature_used', { feature: 'telemetry disabled' });
            this.telemetryDisabledRecorded = true;
        }
    }
    record(eventName, properties) {
        if (this.disabled) {
            this.recordTelemetryDisabled();
        }
        else {
            logger_1.default.debug(`Record event: ${eventName} ${JSON.stringify(properties)}`);
            this.sendEvent(eventName, properties);
        }
    }
    sendEvent(eventName, properties) {
        const propertiesWithMetadata = {
            ...properties,
            packageVersion: constants_1.VERSION,
            isRunningInCi: (0, envars_1.isCI)(),
        };
        if (posthogClient && !(0, envars_1.getEnvBool)('IS_TESTING')) {
            const globalConfig = (0, globalConfig_1.readGlobalConfig)();
            posthogClient.capture({
                distinctId: globalConfig.id,
                event: eventName,
                properties: propertiesWithMetadata,
            });
        }
        const kaBody = {
            profile_id: this.id,
            email: this.email,
            events: [
                {
                    message_id: (0, crypto_1.randomUUID)(),
                    type: 'track',
                    event: eventName,
                    properties: propertiesWithMetadata,
                    sent_at: new Date().toISOString(),
                },
            ],
        };
        fetch(KA_ENDPOINT, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'User-Agent': `promptfoo/${constants_1.VERSION}`,
            },
            body: JSON.stringify(kaBody),
        }).catch(() => {
            // pass
        });
    }
    /**
     * This is a separate endpoint to save consent used only for redteam data synthesis for "harmful" plugins.
     */
    async saveConsent(email, metadata) {
        try {
            const response = await (0, fetch_1.fetchWithTimeout)(CONSENT_ENDPOINT, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ email, metadata }),
            }, TELEMETRY_TIMEOUT_MS);
            if (!response.ok) {
                throw new Error(`Failed to save consent: ${response.statusText}`);
            }
        }
        catch (err) {
            logger_1.default.debug(`Failed to save consent: ${err.message}`);
        }
    }
}
exports.Telemetry = Telemetry;
const telemetry = new Telemetry();
exports.default = telemetry;
//# sourceMappingURL=telemetry.js.map