var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import CaptureSpan from "./CaptureSpan";
import MetricType from "../../../Models/DatabaseModels/MetricType";
import MetricTypeService from "../../Services/MetricTypeService";
import Service from "../../../Models/DatabaseModels/Service";
export default class TelemetryUtil {
    static async indexMetricNameServiceNameMap(data) {
        var _a;
        for (const metricName of Object.keys(data.metricNameServiceNameMap)) {
            // fetch metric
            const metricType = await MetricTypeService.findOneBy({
                query: {
                    projectId: data.projectId,
                    name: metricName,
                },
                select: {
                    services: true,
                    name: true,
                    description: true,
                    unit: true,
                },
                props: {
                    isRoot: true,
                },
            });
            const metricTypeInMap = data.metricNameServiceNameMap[metricName];
            // check if services are same as the ones in the map
            const servicesInMap = ((_a = metricTypeInMap === null || metricTypeInMap === void 0 ? void 0 : metricTypeInMap.services) === null || _a === void 0 ? void 0 : _a.map((service) => {
                return service.id;
            })) || [];
            if (metricType) {
                if (!metricType.services) {
                    metricType.services = [];
                }
                const serviceIds = metricType.services.map((service) => {
                    return service.id;
                });
                let isSame = true;
                // check if description is same
                if (metricType.description !== metricTypeInMap.description) {
                    isSame = false;
                    metricType.description = metricTypeInMap.description || "";
                }
                // check if unit is same
                if (metricType.unit !== metricTypeInMap.unit) {
                    isSame = false;
                    metricType.unit = metricTypeInMap.unit || "";
                }
                // check if services are same
                for (const serviceId of servicesInMap) {
                    if (serviceIds.filter((existingServiceId) => {
                        return existingServiceId.toString() === serviceId.toString();
                    }).length === 0) {
                        isSame = false;
                        // add the service id to the list
                        const service = new Service();
                        service.id = serviceId;
                        metricType.services.push(service);
                    }
                }
                // if its not the same then update the metric type
                if (!isSame) {
                    // update metric type
                    await MetricTypeService.updateOneById({
                        id: metricType.id,
                        data: {
                            services: metricType.services || [],
                            description: metricTypeInMap.description || "",
                            unit: metricTypeInMap.unit || "",
                        },
                        props: {
                            isRoot: true,
                        },
                    });
                }
            }
            else {
                // create metric type
                const metricType = new MetricType();
                metricType.name = metricName;
                metricType.description = metricTypeInMap.description || "";
                metricType.unit = metricTypeInMap.unit || "";
                metricType.projectId = data.projectId;
                metricType.services = [];
                for (const serviceId of servicesInMap) {
                    const service = new Service();
                    service.id = serviceId;
                    metricType.services.push(service);
                }
                // save metric type
                await MetricTypeService.create({
                    data: metricType,
                    props: {
                        isRoot: true,
                    },
                });
            }
        }
    }
    static getAttributesForServiceIdAndServiceName(data) {
        // get attributes for service id and service name
        return {
            "oneuptime.service.id": data.serviceId.toString(),
            "oneuptime.service.name": data.serviceName,
        };
    }
    /*
     * Cross-cutting resource stamps. Spread alongside the service stamp on
     * every analytics row so a single ClickHouse query can find "all
     * telemetry from host X" / "from docker host Y" / "from cluster Z"
     * regardless of which Service the row primarily belongs to. Without
     * these, host context would only be queryable as the raw OTel
     * `resource.host.name` string with no stable id link.
     */
    static getAttributesForHostIdAndHostName(data) {
        return {
            "oneuptime.host.id": data.hostId.toString(),
            "oneuptime.host.name": data.hostName,
        };
    }
    static getAttributesForDockerHostIdAndHostName(data) {
        return {
            "oneuptime.docker.host.id": data.dockerHostId.toString(),
            "oneuptime.docker.host.name": data.hostName,
        };
    }
    static getAttributesForKubernetesClusterIdAndName(data) {
        return {
            "oneuptime.kubernetes.cluster.id": data.kubernetesClusterId.toString(),
            "oneuptime.kubernetes.cluster.name": data.clusterName,
        };
    }
    static getAttributes(data) {
        const { items } = data;
        let { prefixKeysWithString } = data;
        if (prefixKeysWithString) {
            prefixKeysWithString = `${prefixKeysWithString}.`;
        }
        const finalObj = {};
        const attributes = items;
        if (!attributes) {
            return finalObj;
        }
        for (const attribute of attributes) {
            if (!attribute["key"] || typeof attribute["key"] !== "string") {
                continue;
            }
            const keyWithPrefix = `${prefixKeysWithString}${attribute["key"]}`;
            const value = this.getAttributeValues(keyWithPrefix, attribute["value"]);
            if (value === null) {
                finalObj[keyWithPrefix] = null;
                continue;
            }
            if (Array.isArray(value)) {
                finalObj[keyWithPrefix] = value;
                continue;
            }
            if (typeof value === "object") {
                for (const [nestedKey, nestedValue] of Object.entries(value)) {
                    finalObj[nestedKey] = nestedValue;
                }
                continue;
            }
            finalObj[keyWithPrefix] = value;
        }
        return finalObj;
    }
    static getAttributeValues(prefixKeysWithString, value) {
        var _a, _b, _c, _d;
        let finalObj = null;
        const jsonValue = value;
        if (jsonValue && typeof jsonValue === "object") {
            // Handle both camelCase (JSON encoding) and snake_case (protobuf via protobufjs)
            if (Object.prototype.hasOwnProperty.call(jsonValue, "stringValue") ||
                Object.prototype.hasOwnProperty.call(jsonValue, "string_value")) {
                const stringValue = (_a = jsonValue["stringValue"]) !== null && _a !== void 0 ? _a : jsonValue["string_value"];
                finalObj =
                    stringValue !== undefined && stringValue !== null
                        ? stringValue
                        : "";
            }
            else if (Object.prototype.hasOwnProperty.call(jsonValue, "intValue") ||
                Object.prototype.hasOwnProperty.call(jsonValue, "int_value")) {
                const intValue = (_b = jsonValue["intValue"]) !== null && _b !== void 0 ? _b : jsonValue["int_value"];
                if (intValue !== undefined && intValue !== null) {
                    finalObj = intValue;
                }
            }
            else if (Object.prototype.hasOwnProperty.call(jsonValue, "doubleValue") ||
                Object.prototype.hasOwnProperty.call(jsonValue, "double_value")) {
                const doubleValue = (_c = jsonValue["doubleValue"]) !== null && _c !== void 0 ? _c : jsonValue["double_value"];
                if (doubleValue !== undefined && doubleValue !== null) {
                    finalObj = doubleValue;
                }
            }
            else if (Object.prototype.hasOwnProperty.call(jsonValue, "boolValue") ||
                Object.prototype.hasOwnProperty.call(jsonValue, "bool_value")) {
                finalObj = ((_d = jsonValue["boolValue"]) !== null && _d !== void 0 ? _d : jsonValue["bool_value"]);
            }
            else if ((jsonValue["arrayValue"] &&
                jsonValue["arrayValue"]["values"]) ||
                (jsonValue["array_value"] &&
                    jsonValue["array_value"]["values"])) {
                const arrayVal = (jsonValue["arrayValue"] ||
                    jsonValue["array_value"]);
                const values = arrayVal["values"];
                finalObj = values.map((v) => {
                    return this.getAttributeValues(prefixKeysWithString, v);
                });
            }
            else if (jsonValue["mapValue"] &&
                jsonValue["mapValue"]["fields"]) {
                const fields = jsonValue["mapValue"]["fields"];
                const flattenedFields = {};
                for (const key in fields) {
                    const nestedPrefix = `${prefixKeysWithString}.${key}`;
                    const nestedValue = this.getAttributeValues(nestedPrefix, fields[key]);
                    if (nestedValue === null) {
                        flattenedFields[nestedPrefix] = null;
                        continue;
                    }
                    if (Array.isArray(nestedValue)) {
                        flattenedFields[nestedPrefix] = nestedValue;
                        continue;
                    }
                    if (typeof nestedValue === "object") {
                        for (const [nestedKey, nestedEntry] of Object.entries(nestedValue)) {
                            flattenedFields[nestedKey] = nestedEntry;
                        }
                        continue;
                    }
                    flattenedFields[nestedPrefix] = nestedValue;
                }
                finalObj = flattenedFields;
            }
            else if ((jsonValue["kvlistValue"] &&
                jsonValue["kvlistValue"]["values"]) ||
                (jsonValue["kvlist_value"] &&
                    jsonValue["kvlist_value"]["values"])) {
                const kvlistVal = (jsonValue["kvlistValue"] ||
                    jsonValue["kvlist_value"]);
                const values = kvlistVal["values"];
                finalObj = this.getAttributes({
                    prefixKeysWithString,
                    items: values,
                });
            }
            else if ("nullValue" in jsonValue || "null_value" in jsonValue) {
                finalObj = null;
            }
        }
        return finalObj;
    }
    static getAttributeKeys(attributes) {
        if (!attributes || typeof attributes !== "object") {
            return [];
        }
        return Object.keys(attributes).sort();
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], TelemetryUtil, "indexMetricNameServiceNameMap", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Object)
], TelemetryUtil, "getAttributes", null);
//# sourceMappingURL=Telemetry.js.map