import { mapTelemetryErrorCategory, trackTelemetryEvent, validateRegistry, } from '@night-watch/core';
let cliVersion = 'unknown';
let telemetryReporter = (eventName, properties) => trackTelemetryEvent(eventName, properties);
export function setCliTelemetryVersion(version) {
    cliVersion = version;
}
export function setTelemetryReporterForTests(reporter) {
    telemetryReporter = reporter;
}
export function resetTelemetryReporterForTests() {
    telemetryReporter = (eventName, properties) => trackTelemetryEvent(eventName, properties);
}
function getNodeMajorVersion() {
    const major = parseInt(process.versions.node.split('.')[0] ?? '0', 10);
    return Number.isNaN(major) ? 0 : major;
}
function getRegisteredProjectCount() {
    try {
        return validateRegistry().valid.length;
    }
    catch {
        return 0;
    }
}
export function buildTelemetryBaseProperties(config) {
    return {
        cliVersion,
        platform: process.platform,
        nodeMajorVersion: getNodeMajorVersion(),
        boardMode: config ? config.boardProvider?.enabled !== false : undefined,
        registeredProjectCount: getRegisteredProjectCount(),
    };
}
export function fireTelemetryEvent(eventName, properties = {}) {
    void telemetryReporter(eventName, properties).catch(() => undefined);
}
export async function trackCommandStarted(command, config) {
    await telemetryReporter('command_started', {
        ...buildTelemetryBaseProperties(config),
        command,
    }).catch(() => undefined);
}
export async function trackCommandCompleted(command, startedAt, exitCode, config, extraProps = {}) {
    await telemetryReporter('command_completed', {
        ...buildTelemetryBaseProperties(config),
        ...extraProps,
        command,
        durationMs: Math.max(0, Date.now() - startedAt),
        exitCode,
        success: exitCode === 0,
        failure: exitCode !== 0,
    }).catch(() => undefined);
}
export async function trackJobStarted(jobType, provider, config) {
    await telemetryReporter('job_started', {
        ...buildTelemetryBaseProperties(config),
        jobType,
        provider,
    }).catch(() => undefined);
}
export async function trackJobCompletedOrFailed(jobType, provider, startedAt, exitCode, config, errorCategory) {
    await telemetryReporter(exitCode === 0 ? 'job_completed' : 'job_failed', {
        ...buildTelemetryBaseProperties(config),
        jobType,
        provider,
        durationMs: Math.max(0, Date.now() - startedAt),
        exitCode,
        success: exitCode === 0,
        failure: exitCode !== 0,
        errorCategory: exitCode === 0 ? undefined : mapTelemetryErrorCategory(errorCategory),
    }).catch(() => undefined);
}
//# sourceMappingURL=telemetry.js.map