import { POST_HOG_CAPTURE_KEY, POST_HOG_HOST, ZUPLO_USER_ID_ARGV_KEY, } from "../constants.js";
import { machineId } from "../machine-id/lib.js";
import { getPackageManagerUsageProperties } from "./package-manager.js";
const ANALYTICS_FLUSH_TIMEOUT_MS = 2000;
let _postHog;
let _initialized = false;
let _userContext = {};
async function withTimeout(promise, ms) {
    let timer;
    const timeout = new Promise((resolve) => {
        timer = setTimeout(resolve, ms);
        timer.unref?.();
    });
    await Promise.race([promise.catch(() => undefined), timeout]);
    if (timer) {
        clearTimeout(timer);
    }
}
async function init() {
    if (process.env.ZUPLO_DO_NOT_TRACK) {
        return undefined;
    }
    if (_initialized) {
        return _postHog;
    }
    _initialized = true;
    try {
        const { PostHog } = await import("posthog-node");
        _postHog = new PostHog(POST_HOG_CAPTURE_KEY, {
            host: POST_HOG_HOST,
            flushAt: 1,
            flushInterval: 1,
        });
    }
    catch {
        _postHog = undefined;
    }
    return _postHog;
}
export function setUserContext(context) {
    _userContext = { ..._userContext, ...context };
}
function getDistinctId() {
    return _userContext.distinctId ?? machineId();
}
export async function captureEvent({ argv, event, properties, groups, sendFeatureFlags, timestamp, disableGeoip, }) {
    const posthog = await init();
    if (posthog) {
        properties = {
            ...getPackageManagerUsageProperties(),
            ...(properties ?? {}),
        };
        properties.$set_once = properties.$set_once ?? {};
        if (argv[ZUPLO_USER_ID_ARGV_KEY] &&
            typeof argv[ZUPLO_USER_ID_ARGV_KEY] === "string") {
            properties.$set_once["user-id"] = argv[ZUPLO_USER_ID_ARGV_KEY];
        }
        if (argv.account && typeof argv.account === "string") {
            properties.$set_once["account"] = argv["account"];
        }
        if (argv.project && typeof argv.project === "string") {
            properties.$set_once["project"] = argv["project"];
        }
        if (process.env.CI) {
            properties["ci"] = process.env.CI;
        }
        posthog.capture({
            distinctId: argv[ZUPLO_USER_ID_ARGV_KEY] || machineId(),
            event,
            properties,
            groups,
            sendFeatureFlags,
            timestamp,
            disableGeoip,
        });
    }
}
export async function captureError(error, properties) {
    const posthog = await init();
    if (!posthog) {
        return;
    }
    try {
        const contextProperties = {};
        if (_userContext.account) {
            contextProperties["account"] = _userContext.account;
        }
        if (_userContext.project) {
            contextProperties["project"] = _userContext.project;
        }
        if (process.env.CI) {
            contextProperties["ci"] = process.env.CI;
        }
        await withTimeout(posthog.captureExceptionImmediate(error, getDistinctId(), {
            ...contextProperties,
            ...(properties ?? {}),
        }), ANALYTICS_FLUSH_TIMEOUT_MS);
    }
    catch {
    }
}
export async function shutdownAnalytics() {
    if (!_postHog) {
        return;
    }
    await withTimeout(_postHog.shutdown(), ANALYTICS_FLUSH_TIMEOUT_MS);
}
//# sourceMappingURL=lib.js.map