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 Alert from "../../Models/DatabaseModels/Alert";
import AlertLabelRule from "../../Models/DatabaseModels/AlertLabelRule";
import Label from "../../Models/DatabaseModels/Label";
import AlertFeedService from "./AlertFeedService";
import AlertLabelRuleService from "./AlertLabelRuleService";
import AlertService from "./AlertService";
import DockerHostService from "./DockerHostService";
import HostService from "./HostService";
import KubernetesClusterService from "./KubernetesClusterService";
import LabelService from "./LabelService";
import MonitorService from "./MonitorService";
import ServiceService from "./ServiceService";
import { AlertFeedEventType } from "../../Models/DatabaseModels/AlertFeed";
import { Indigo500 } from "../../Types/BrandColors";
import ObjectID from "../../Types/ObjectID";
import LIMIT_MAX from "../../Types/Database/LimitMax";
import QueryHelper from "../Types/Database/QueryHelper";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
class AlertLabelRuleEngineServiceClass {
    /**
     * Evaluates AlertLabelRule rows for the given alert and attaches matched
     * labels to the alert. Each matched rule contributes:
     *   - labels listed on `labelsToAdd`
     *   - all labels of the alert's monitor when `inheritLabelsFromMonitors`
     *   - all labels of the alert's hosts when `inheritLabelsFromHosts`
     *   - all labels of the alert's Kubernetes clusters when `inheritLabelsFromKubernetesClusters`
     *   - all labels of the alert's Docker hosts when `inheritLabelsFromDockerHosts`
     *   - all labels of the alert's services when `inheritLabelsFromServices`
     * The union is deduped against labels already on the alert before insert
     * to avoid PK conflicts on the AlertLabel join table.
     */
    async applyRulesToAlert(alert) {
        var _a, _b, _c, _d, _e, _f;
        if (!alert.id || !alert.projectId) {
            return;
        }
        try {
            const rules = await AlertLabelRuleService.findBy({
                query: {
                    projectId: alert.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    monitors: { _id: true },
                    alertSeverities: { _id: true },
                    alertLabels: { _id: true },
                    monitorLabels: { _id: true },
                    alertTitlePattern: true,
                    alertDescriptionPattern: true,
                    monitorNamePattern: true,
                    monitorDescriptionPattern: true,
                    labelsToAdd: { _id: true },
                    inheritLabelsFromMonitors: true,
                    inheritLabelsFromHosts: true,
                    inheritLabelsFromKubernetesClusters: true,
                    inheritLabelsFromDockerHosts: true,
                    inheritLabelsFromServices: true,
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const labelIdsToAdd = new Set();
            let inheritFromMonitors = false;
            let inheritFromHosts = false;
            let inheritFromKubernetesClusters = false;
            let inheritFromDockerHosts = false;
            let inheritFromServices = false;
            const matchedRules = [];
            for (const rule of rules) {
                const matches = await this.doesAlertMatchRule(alert, rule);
                if (!matches) {
                    continue;
                }
                matchedRules.push(rule);
                for (const label of rule.labelsToAdd || []) {
                    if (label.id) {
                        labelIdsToAdd.add(label.id.toString());
                    }
                }
                if (rule.inheritLabelsFromMonitors) {
                    inheritFromMonitors = true;
                }
                if (rule.inheritLabelsFromHosts) {
                    inheritFromHosts = true;
                }
                if (rule.inheritLabelsFromKubernetesClusters) {
                    inheritFromKubernetesClusters = true;
                }
                if (rule.inheritLabelsFromDockerHosts) {
                    inheritFromDockerHosts = true;
                }
                if (rule.inheritLabelsFromServices) {
                    inheritFromServices = true;
                }
            }
            const needsRelatedResources = inheritFromHosts ||
                inheritFromKubernetesClusters ||
                inheritFromDockerHosts ||
                inheritFromServices;
            let alertWithResources = null;
            if (needsRelatedResources) {
                alertWithResources = await AlertService.findOneById({
                    id: alert.id,
                    select: {
                        hosts: { _id: true },
                        kubernetesClusters: { _id: true },
                        dockerHosts: { _id: true },
                        services: { _id: true },
                    },
                    props: { isRoot: true },
                });
            }
            if (inheritFromMonitors && alert.monitorId) {
                const monitor = await MonitorService.findOneById({
                    id: alert.monitorId,
                    select: { labels: { _id: true } },
                    props: { isRoot: true },
                });
                for (const label of (monitor === null || monitor === void 0 ? void 0 : monitor.labels) || []) {
                    if (label.id) {
                        labelIdsToAdd.add(label.id.toString());
                    }
                }
            }
            if (inheritFromHosts && ((_a = alertWithResources === null || alertWithResources === void 0 ? void 0 : alertWithResources.hosts) === null || _a === void 0 ? void 0 : _a.length)) {
                for (const alertHost of alertWithResources.hosts) {
                    if (!alertHost.id) {
                        continue;
                    }
                    const host = await HostService.findOneById({
                        id: alertHost.id,
                        select: { labels: { _id: true } },
                        props: { isRoot: true },
                    });
                    for (const label of (host === null || host === void 0 ? void 0 : host.labels) || []) {
                        if (label.id) {
                            labelIdsToAdd.add(label.id.toString());
                        }
                    }
                }
            }
            if (inheritFromKubernetesClusters &&
                ((_b = alertWithResources === null || alertWithResources === void 0 ? void 0 : alertWithResources.kubernetesClusters) === null || _b === void 0 ? void 0 : _b.length)) {
                for (const alertCluster of alertWithResources.kubernetesClusters) {
                    if (!alertCluster.id) {
                        continue;
                    }
                    const cluster = await KubernetesClusterService.findOneById({
                        id: alertCluster.id,
                        select: { labels: { _id: true } },
                        props: { isRoot: true },
                    });
                    for (const label of (cluster === null || cluster === void 0 ? void 0 : cluster.labels) || []) {
                        if (label.id) {
                            labelIdsToAdd.add(label.id.toString());
                        }
                    }
                }
            }
            if (inheritFromDockerHosts && ((_c = alertWithResources === null || alertWithResources === void 0 ? void 0 : alertWithResources.dockerHosts) === null || _c === void 0 ? void 0 : _c.length)) {
                for (const alertDockerHost of alertWithResources.dockerHosts) {
                    if (!alertDockerHost.id) {
                        continue;
                    }
                    const dockerHost = await DockerHostService.findOneById({
                        id: alertDockerHost.id,
                        select: { labels: { _id: true } },
                        props: { isRoot: true },
                    });
                    for (const label of (dockerHost === null || dockerHost === void 0 ? void 0 : dockerHost.labels) || []) {
                        if (label.id) {
                            labelIdsToAdd.add(label.id.toString());
                        }
                    }
                }
            }
            if (inheritFromServices && ((_d = alertWithResources === null || alertWithResources === void 0 ? void 0 : alertWithResources.services) === null || _d === void 0 ? void 0 : _d.length)) {
                for (const alertService of alertWithResources.services) {
                    if (!alertService.id) {
                        continue;
                    }
                    const service = await ServiceService.findOneById({
                        id: alertService.id,
                        select: { labels: { _id: true } },
                        props: { isRoot: true },
                    });
                    for (const label of (service === null || service === void 0 ? void 0 : service.labels) || []) {
                        if (label.id) {
                            labelIdsToAdd.add(label.id.toString());
                        }
                    }
                }
            }
            if (labelIdsToAdd.size === 0) {
                return;
            }
            const alertWithLabels = await AlertService.findOneById({
                id: alert.id,
                select: { labels: { _id: true } },
                props: { isRoot: true },
            });
            const existingLabelIds = new Set(((alertWithLabels === null || alertWithLabels === void 0 ? void 0 : alertWithLabels.labels) || [])
                .map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            })
                .filter((id) => {
                return id !== "";
            }));
            const newLabelIds = Array.from(labelIdsToAdd).filter((id) => {
                return !existingLabelIds.has(id);
            });
            if (newLabelIds.length === 0) {
                return;
            }
            await AlertService.getRepository()
                .createQueryBuilder()
                .relation(Alert, "labels")
                .of(alert.id.toString())
                .add(newLabelIds);
            /*
             * Sync in-memory alert.labels with the now-persisted set so downstream
             * rule engines (AlertOnCallRuleEngineService) can match on these labels
             * in the same onCreateSuccess chain. Without this, the on-call engine sees
             * only the criteria-time labels and skips rules keyed on rule-added labels.
             */
            const mergedLabelIds = new Set([
                ...existingLabelIds,
                ...newLabelIds,
            ]);
            alert.labels = Array.from(mergedLabelIds).map((id) => {
                const label = new Label();
                label.id = new ObjectID(id);
                return label;
            });
            logger.debug(`AlertLabelRuleEngine attached ${newLabelIds.length} labels to alert ${alert.id}`, { projectId: alert.projectId.toString() });
            await this.createRuleExecutedFeedItem({
                alert,
                matchedRules,
                addedLabelIds: newLabelIds,
            });
        }
        catch (error) {
            logger.error(`Error applying alert label rules: ${error}`, {
                projectId: (_e = alert.projectId) === null || _e === void 0 ? void 0 : _e.toString(),
                alertId: (_f = alert.id) === null || _f === void 0 ? void 0 : _f.toString(),
            });
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { alert, matchedRules, addedLabelIds } = data;
        if (!alert.id ||
            !alert.projectId ||
            matchedRules.length === 0 ||
            addedLabelIds.length === 0) {
            return;
        }
        try {
            const labelObjectIds = addedLabelIds.map((id) => {
                return new ObjectID(id);
            });
            const labels = await LabelService.findBy({
                query: {
                    _id: QueryHelper.any(labelObjectIds),
                },
                select: { name: true },
                props: { isRoot: true },
                limit: LIMIT_MAX,
                skip: 0,
            });
            const labelNames = labels
                .map((l) => {
                var _a;
                return ((_a = l.name) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            })
                .filter((n) => {
                return n !== "";
            });
            const ruleNames = matchedRules
                .map((r) => {
                var _a;
                return ((_a = r.name) === null || _a === void 0 ? void 0 : _a.toString()) || "Unnamed Rule";
            })
                .filter((n) => {
                return n !== "";
            });
            const rulesPart = ruleNames.length === 1
                ? `**${ruleNames[0]}**`
                : ruleNames
                    .map((n) => {
                    return `**${n}**`;
                })
                    .join(", ");
            const labelsPart = labelNames.length > 0
                ? labelNames
                    .map((n) => {
                    return `\n- ${n}`;
                })
                    .join("")
                : "\n- (no named labels)";
            const feedInfoInMarkdown = `🏷️ **Alert Label Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAdded the following label${labelNames.length === 1 ? "" : "s"} to the alert:${labelsPart}`;
            await AlertFeedService.createAlertFeedItem({
                alertId: alert.id,
                projectId: alert.projectId,
                alertFeedEventType: AlertFeedEventType.LabelRuleExecuted,
                displayColor: Indigo500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`AlertLabelRuleEngine: failed to create rule-executed feed item: ${error instanceof Error ? error.message : String(error)}`, {
                projectId: (_a = alert.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                alertId: (_b = alert.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    async doesAlertMatchRule(alert, rule) {
        if (rule.monitors && rule.monitors.length > 0) {
            if (!alert.monitorId) {
                return false;
            }
            const ruleMonitorIds = rule.monitors.map((m) => {
                var _a;
                return ((_a = m.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleMonitorIds.includes(alert.monitorId.toString())) {
                return false;
            }
        }
        if (rule.alertSeverities && rule.alertSeverities.length > 0) {
            if (!alert.alertSeverityId) {
                return false;
            }
            const severityIds = rule.alertSeverities.map((s) => {
                var _a;
                return ((_a = s.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!severityIds.includes(alert.alertSeverityId.toString())) {
                return false;
            }
        }
        if (rule.alertLabels && rule.alertLabels.length > 0) {
            if (!alert.labels || alert.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.alertLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const alertLabelIds = alert.labels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleLabelIds.some((id) => {
                return alertLabelIds.includes(id);
            })) {
                return false;
            }
        }
        const hasMonitorCriteria = Boolean((rule.monitorLabels && rule.monitorLabels.length > 0) ||
            rule.monitorNamePattern ||
            rule.monitorDescriptionPattern);
        if (hasMonitorCriteria) {
            if (!alert.monitorId) {
                return false;
            }
            const monitor = await MonitorService.findOneById({
                id: alert.monitorId,
                select: {
                    name: true,
                    description: true,
                    labels: { _id: true },
                },
                props: { isRoot: true },
            });
            if (!monitor) {
                return false;
            }
            if (rule.monitorLabels && rule.monitorLabels.length > 0) {
                if (!monitor.labels || monitor.labels.length === 0) {
                    return false;
                }
                const ruleMonitorLabelIds = rule.monitorLabels.map((l) => {
                    var _a;
                    return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
                });
                const monitorLabelIds = monitor.labels.map((l) => {
                    var _a;
                    return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
                });
                if (!ruleMonitorLabelIds.some((id) => {
                    return monitorLabelIds.includes(id);
                })) {
                    return false;
                }
            }
            if (rule.monitorNamePattern &&
                (!monitor.name ||
                    !this.testRegex(rule.monitorNamePattern, monitor.name, rule))) {
                return false;
            }
            if (rule.monitorDescriptionPattern &&
                (!monitor.description ||
                    !this.testRegex(rule.monitorDescriptionPattern, monitor.description, rule))) {
                return false;
            }
        }
        if (rule.alertTitlePattern &&
            (!alert.title ||
                !this.testRegex(rule.alertTitlePattern, alert.title, rule))) {
            return false;
        }
        if (rule.alertDescriptionPattern &&
            (!alert.description ||
                !this.testRegex(rule.alertDescriptionPattern, alert.description, rule))) {
            return false;
        }
        return true;
    }
    testRegex(pattern, value, rule) {
        try {
            const regex = new RegExp(pattern, "i");
            return regex.test(value);
        }
        catch (_a) {
            logger.warn(`Invalid regex in alert label rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Alert]),
    __metadata("design:returntype", Promise)
], AlertLabelRuleEngineServiceClass.prototype, "applyRulesToAlert", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], AlertLabelRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Alert,
        AlertLabelRule]),
    __metadata("design:returntype", Promise)
], AlertLabelRuleEngineServiceClass.prototype, "doesAlertMatchRule", null);
export default new AlertLabelRuleEngineServiceClass();
//# sourceMappingURL=AlertLabelRuleEngineService.js.map