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 Incident from "../../Models/DatabaseModels/Incident";
import IncidentLabelRule from "../../Models/DatabaseModels/IncidentLabelRule";
import Label from "../../Models/DatabaseModels/Label";
import DockerHostService from "./DockerHostService";
import HostService from "./HostService";
import IncidentFeedService from "./IncidentFeedService";
import IncidentLabelRuleService from "./IncidentLabelRuleService";
import IncidentService from "./IncidentService";
import KubernetesClusterService from "./KubernetesClusterService";
import LabelService from "./LabelService";
import MonitorService from "./MonitorService";
import ServiceService from "./ServiceService";
import { IncidentFeedEventType } from "../../Models/DatabaseModels/IncidentFeed";
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 IncidentLabelRuleEngineServiceClass {
    /**
     * Evaluates IncidentLabelRule rows for the given incident and attaches
     * matched labels to the incident. Each matched rule contributes:
     *   - labels listed on `labelsToAdd`
     *   - all labels of the incident's monitors when `inheritLabelsFromMonitors`
     *   - all labels of the incident's hosts when `inheritLabelsFromHosts`
     *   - all labels of the incident's Kubernetes clusters when `inheritLabelsFromKubernetesClusters`
     *   - all labels of the incident's Docker hosts when `inheritLabelsFromDockerHosts`
     *   - all labels of the incident's services when `inheritLabelsFromServices`
     * The union is deduped against labels already on the incident before insert
     * to avoid PK conflicts on the IncidentLabel join table.
     */
    async applyRulesToIncident(incident) {
        var _a, _b, _c, _d, _e, _f, _g;
        if (!incident.id || !incident.projectId) {
            return;
        }
        try {
            const rules = await IncidentLabelRuleService.findBy({
                query: {
                    projectId: incident.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    monitors: { _id: true },
                    incidentSeverities: { _id: true },
                    incidentLabels: { _id: true },
                    monitorLabels: { _id: true },
                    incidentTitlePattern: true,
                    incidentDescriptionPattern: 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.doesIncidentMatchRule(incident, 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;
                }
            }
            if (inheritFromMonitors && ((_a = incident.monitors) === null || _a === void 0 ? void 0 : _a.length)) {
                for (const incidentMonitor of incident.monitors) {
                    if (!incidentMonitor.id) {
                        continue;
                    }
                    const monitor = await MonitorService.findOneById({
                        id: incidentMonitor.id,
                        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 && ((_b = incident.hosts) === null || _b === void 0 ? void 0 : _b.length)) {
                for (const incidentHost of incident.hosts) {
                    if (!incidentHost.id) {
                        continue;
                    }
                    const host = await HostService.findOneById({
                        id: incidentHost.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 &&
                ((_c = incident.kubernetesClusters) === null || _c === void 0 ? void 0 : _c.length)) {
                for (const incidentCluster of incident.kubernetesClusters) {
                    if (!incidentCluster.id) {
                        continue;
                    }
                    const cluster = await KubernetesClusterService.findOneById({
                        id: incidentCluster.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 && ((_d = incident.dockerHosts) === null || _d === void 0 ? void 0 : _d.length)) {
                for (const incidentDockerHost of incident.dockerHosts) {
                    if (!incidentDockerHost.id) {
                        continue;
                    }
                    const dockerHost = await DockerHostService.findOneById({
                        id: incidentDockerHost.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 && ((_e = incident.services) === null || _e === void 0 ? void 0 : _e.length)) {
                for (const incidentService of incident.services) {
                    if (!incidentService.id) {
                        continue;
                    }
                    const service = await ServiceService.findOneById({
                        id: incidentService.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 incidentWithLabels = await IncidentService.findOneById({
                id: incident.id,
                select: { labels: { _id: true } },
                props: { isRoot: true },
            });
            const existingLabelIds = new Set(((incidentWithLabels === null || incidentWithLabels === void 0 ? void 0 : incidentWithLabels.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 IncidentService.getRepository()
                .createQueryBuilder()
                .relation(Incident, "labels")
                .of(incident.id.toString())
                .add(newLabelIds);
            /*
             * Sync in-memory incident.labels with the now-persisted set so downstream
             * rule engines (IncidentOnCallRuleEngineService) 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,
            ]);
            incident.labels = Array.from(mergedLabelIds).map((id) => {
                const label = new Label();
                label.id = new ObjectID(id);
                return label;
            });
            logger.debug(`IncidentLabelRuleEngine attached ${newLabelIds.length} labels to incident ${incident.id}`, { projectId: incident.projectId.toString() });
            await this.createRuleExecutedFeedItem({
                incident,
                matchedRules,
                addedLabelIds: newLabelIds,
            });
        }
        catch (error) {
            logger.error(`Error applying incident label rules: ${error}`, {
                projectId: (_f = incident.projectId) === null || _f === void 0 ? void 0 : _f.toString(),
                incidentId: (_g = incident.id) === null || _g === void 0 ? void 0 : _g.toString(),
            });
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { incident, matchedRules, addedLabelIds } = data;
        if (!incident.id ||
            !incident.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 = `🏷️ **Incident Label Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAdded the following label${labelNames.length === 1 ? "" : "s"} to the incident:${labelsPart}`;
            await IncidentFeedService.createIncidentFeedItem({
                incidentId: incident.id,
                projectId: incident.projectId,
                incidentFeedEventType: IncidentFeedEventType.LabelRuleExecuted,
                displayColor: Indigo500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`IncidentLabelRuleEngine: failed to create rule-executed feed item: ${error instanceof Error ? error.message : String(error)}`, {
                projectId: (_a = incident.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                incidentId: (_b = incident.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    async doesIncidentMatchRule(incident, rule) {
        if (rule.monitors && rule.monitors.length > 0) {
            if (!incident.monitors || incident.monitors.length === 0) {
                return false;
            }
            const ruleMonitorIds = rule.monitors.map((m) => {
                var _a;
                return ((_a = m.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const incidentMonitorIds = incident.monitors.map((m) => {
                var _a;
                return ((_a = m.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleMonitorIds.some((id) => {
                return incidentMonitorIds.includes(id);
            })) {
                return false;
            }
        }
        if (rule.incidentSeverities && rule.incidentSeverities.length > 0) {
            if (!incident.incidentSeverityId) {
                return false;
            }
            const severityIds = rule.incidentSeverities.map((s) => {
                var _a;
                return ((_a = s.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!severityIds.includes(incident.incidentSeverityId.toString())) {
                return false;
            }
        }
        if (rule.incidentLabels && rule.incidentLabels.length > 0) {
            if (!incident.labels || incident.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.incidentLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const incidentLabelIds = incident.labels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleLabelIds.some((id) => {
                return incidentLabelIds.includes(id);
            })) {
                return false;
            }
        }
        const hasMonitorCriteria = Boolean((rule.monitorLabels && rule.monitorLabels.length > 0) ||
            rule.monitorNamePattern ||
            rule.monitorDescriptionPattern);
        if (hasMonitorCriteria) {
            if (!incident.monitors || incident.monitors.length === 0) {
                return false;
            }
            let anyMonitorMatches = false;
            for (const incidentMonitor of incident.monitors) {
                if (!incidentMonitor.id) {
                    continue;
                }
                const monitor = await MonitorService.findOneById({
                    id: incidentMonitor.id,
                    select: {
                        name: true,
                        description: true,
                        labels: { _id: true },
                    },
                    props: { isRoot: true },
                });
                if (!monitor) {
                    continue;
                }
                let monitorMatches = true;
                if (rule.monitorLabels && rule.monitorLabels.length > 0) {
                    if (!monitor.labels || monitor.labels.length === 0) {
                        monitorMatches = false;
                    }
                    else {
                        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);
                        })) {
                            monitorMatches = false;
                        }
                    }
                }
                if (monitorMatches &&
                    rule.monitorNamePattern &&
                    (!monitor.name ||
                        !this.testRegex(rule.monitorNamePattern, monitor.name, rule))) {
                    monitorMatches = false;
                }
                if (monitorMatches &&
                    rule.monitorDescriptionPattern &&
                    (!monitor.description ||
                        !this.testRegex(rule.monitorDescriptionPattern, monitor.description, rule))) {
                    monitorMatches = false;
                }
                if (monitorMatches) {
                    anyMonitorMatches = true;
                    break;
                }
            }
            if (!anyMonitorMatches) {
                return false;
            }
        }
        if (rule.incidentTitlePattern &&
            (!incident.title ||
                !this.testRegex(rule.incidentTitlePattern, incident.title, rule))) {
            return false;
        }
        if (rule.incidentDescriptionPattern &&
            (!incident.description ||
                !this.testRegex(rule.incidentDescriptionPattern, incident.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 incident label rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Incident]),
    __metadata("design:returntype", Promise)
], IncidentLabelRuleEngineServiceClass.prototype, "applyRulesToIncident", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], IncidentLabelRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Incident,
        IncidentLabelRule]),
    __metadata("design:returntype", Promise)
], IncidentLabelRuleEngineServiceClass.prototype, "doesIncidentMatchRule", null);
export default new IncidentLabelRuleEngineServiceClass();
//# sourceMappingURL=IncidentLabelRuleEngineService.js.map