"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.trackMcpEvent = trackMcpEvent;
exports.trackCliEvent = trackCliEvent;
exports.trackExternalToolEvent = trackExternalToolEvent;
exports.trackMablTestsRunnerEvent = trackMablTestsRunnerEvent;
const env_1 = require("../env/env");
const cliConfigProvider_1 = require("../providers/cliConfigProvider");
const pureUtil_1 = require("./pureUtil");
const os = __importStar(require("os"));
const types_1 = require("../api/types");
const loggingProvider_1 = require("../providers/logging/loggingProvider");
const configKeys_1 = require("../providers/configKeys");
const analytics_node_1 = require("@segment/analytics-node");
const segmentHttpClient_1 = require("../http/segmentHttpClient");
function getCliUserId(workspaceId) {
    return `cliKey-${workspaceId ?? 'unknown'}`;
}
async function getTrackingInfo() {
    const config = await cliConfigProvider_1.CliConfigProvider.getCliConfig();
    if (config.authentication.authType === undefined) {
        return {};
    }
    let userId;
    if (config.authentication.authType === types_1.AuthType.ApiKey) {
        userId = `cliKey-${config.workspace?.id ?? 'unknown'}`;
        userId = getCliUserId(config.workspace?.id);
    }
    else {
        userId = config.userId;
    }
    const scmDetectionEnabled = (await cliConfigProvider_1.CliConfigProvider.getConfigProperty(configKeys_1.configKeys.enableSourceControlMetadataCollection)) ?? false;
    return {
        userId,
        workspaceId: config.workspace?.id,
        features: {
            scm_metadata: scmDetectionEnabled,
        },
    };
}
async function trackMcpEvent(command) {
    try {
        const trackingInfo = await getTrackingInfo();
        if (!trackingInfo.userId) {
            return;
        }
        const event = 'mablMcp - Tool Used';
        const properties = {
            workspaceId: trackingInfo.workspaceId,
            environment: env_1.ENV,
            mcpToolName: command,
        };
        trackEvent(event, trackingInfo.userId, properties);
    }
    catch (error) {
        if (env_1.ENV === 'local' || env_1.ENV === 'dev') {
            loggingProvider_1.logger.error('Error with Segment event', error);
        }
    }
}
async function trackCliEvent(commands, argumentCountMap) {
    try {
        const trackingInfo = await getTrackingInfo();
        if (!trackingInfo.userId) {
            return;
        }
        const event = `mablCli - ${commands.join(' ')}`;
        const properties = {
            workspaceId: trackingInfo.workspaceId,
            environment: env_1.ENV,
            argumentCountMap,
            features: trackingInfo.features,
        };
        trackEvent(event, trackingInfo.userId, properties);
    }
    catch (error) {
        if (env_1.ENV === 'local' || env_1.ENV === 'dev') {
            loggingProvider_1.logger.error('Error with Segment event', error);
        }
    }
}
function trackExternalToolEvent(event, properties) {
    try {
        getAnalytics().track({
            userId: getCliUserId(properties.workspaceId),
            event,
            context: {
                app: {
                    build: env_1.ENV,
                    name: (0, pureUtil_1.getCliName)(),
                    version: (0, pureUtil_1.getCliVersion)(),
                },
                os: {
                    name: os.platform(),
                    version: os.release(),
                },
                groupId: properties.workspaceId,
                userAgent: getUserAgent(),
            },
            properties,
        });
    }
    catch (error) {
        loggingProvider_1.logger.error('Error with analytics data', error);
    }
}
async function trackMablTestsRunnerEvent(eventName, resultsMap) {
    try {
        const trackingInfo = await getTrackingInfo();
        if (!trackingInfo.userId) {
            return;
        }
        const properties = {
            workspaceId: trackingInfo.workspaceId,
            environment: env_1.ENV,
            resultsMap,
        };
        trackEvent(eventName, trackingInfo.userId, properties);
    }
    catch (error) {
        if (env_1.ENV === 'local' || env_1.ENV === 'dev') {
            loggingProvider_1.logger.error('Error with Segment event', error);
        }
    }
}
function trackEvent(event, userId, properties) {
    const cpuInfo = os.cpus() ?? [];
    getAnalytics().track({
        userId,
        event,
        context: {
            app: {
                build: env_1.ENV,
                name: (0, pureUtil_1.getCliName)(),
                version: (0, pureUtil_1.getCliVersion)(),
            },
            os: {
                name: os.platform(),
                version: os.release(),
            },
            groupId: properties.workspaceId,
            userAgent: getUserAgent(),
            device: {
                cpuCount: cpuInfo.length,
                cpuType: cpuInfo?.[0]?.model,
                cpuSpeed: cpuInfo?.[0]?.speed,
                osArch: os.arch(),
                memFree: os.freemem(),
                memTotal: os.totalmem(),
            },
        },
        properties,
    });
}
let analyticsInstance;
function getAnalytics() {
    if (!analyticsInstance) {
        analyticsInstance = new analytics_node_1.Analytics({
            writeKey: 'ghbAXZbk8fqWROgMscPdkQMoqEjwsKRa',
            httpClient: new segmentHttpClient_1.ProxyAwareHTTPClient(),
            flushAt: 1,
            flushInterval: 1,
        });
        analyticsInstance.on('error', (error) => {
            if (env_1.ENV === 'local' || env_1.ENV === 'dev') {
                loggingProvider_1.logger.error('Error with Segment event', error);
            }
        });
    }
    return analyticsInstance;
}
function getUserAgent() {
    const nodeName = process?.release?.name ?? 'node';
    return `${nodeName}_${process.arch}@${process.version}`;
}
