import Pyroscope from "@pyroscope/nodejs";
import { EnableProfiling } from "../EnvironmentConfig";
import logger from "./Logger";
import GracefulShutdown, { ShutdownPriority } from "./GracefulShutdown";
export default class Profiling {
    static init(data) {
        if (!EnableProfiling) {
            return;
        }
        const serverAddress = this.getServerAddress();
        const authToken = this.getAuthToken();
        const profilingLogAttributes = {
            serviceName: data.serviceName,
        };
        if (!serverAddress) {
            logger.warn("Profiling enabled but OPENTELEMETRY_EXPORTER_OTLP_ENDPOINT not configured. Skipping profiling initialization.", profilingLogAttributes);
            return;
        }
        try {
            Pyroscope.init({
                appName: data.serviceName,
                serverAddress: serverAddress,
                authToken: authToken,
                wall: {
                    collectCpuTime: true,
                },
            });
            Pyroscope.start();
            logger.info(`Profiling initialized for service: ${data.serviceName} -> ${serverAddress}`, profilingLogAttributes);
        }
        catch (err) {
            logger.error("Failed to initialize profiling:", profilingLogAttributes);
            logger.error(err, profilingLogAttributes);
        }
        // Stop the profiler last (Telemetry tier), alongside the OTEL flush.
        GracefulShutdown.registerHandler("Profiling", ShutdownPriority.Telemetry, async () => {
            try {
                await Pyroscope.stop();
            }
            catch (err) {
                logger.error("Error stopping profiler:", profilingLogAttributes);
                logger.error(err, profilingLogAttributes);
            }
        });
    }
    static getServerAddress() {
        /*
         * Use the OTLP endpoint base URL as the Pyroscope server address.
         * The Pyroscope SDK will append /ingest to this URL.
         * The final URL will be /pyroscope/ingest, routed by nginx to the telemetry service.
         */
        const endpoint = process.env["OPENTELEMETRY_EXPORTER_OTLP_ENDPOINT"];
        if (!endpoint) {
            return undefined;
        }
        /*
         * Strip /otlp suffix if present and append /pyroscope
         * The Pyroscope SDK appends /ingest, so the final URL will be /pyroscope/ingest
         */
        let baseUrl = endpoint;
        if (baseUrl.endsWith("/otlp")) {
            baseUrl = baseUrl.substring(0, baseUrl.length - 5);
        }
        if (baseUrl.endsWith("/")) {
            baseUrl = baseUrl.substring(0, baseUrl.length - 1);
        }
        return `${baseUrl}/pyroscope`;
    }
    static getAuthToken() {
        /*
         * Extract the OneUptime token from OTLP headers
         * Format: "x-oneuptime-token=<value>;other-header=value"
         */
        const headersStr = process.env["OPENTELEMETRY_EXPORTER_OTLP_HEADERS"];
        if (!headersStr) {
            return undefined;
        }
        const parts = headersStr.split(";");
        for (const part of parts) {
            const [key, value] = part.split("=");
            if (key === "x-oneuptime-token" && value) {
                return value;
            }
        }
        return undefined;
    }
}
//# sourceMappingURL=Profiling.js.map