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 Label from "../../Models/DatabaseModels/Label";
import ScheduledMaintenance from "../../Models/DatabaseModels/ScheduledMaintenance";
import ScheduledMaintenanceLabelRule from "../../Models/DatabaseModels/ScheduledMaintenanceLabelRule";
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 ScheduledMaintenanceFeedService from "./ScheduledMaintenanceFeedService";
import ScheduledMaintenanceLabelRuleService from "./ScheduledMaintenanceLabelRuleService";
import ScheduledMaintenanceService from "./ScheduledMaintenanceService";
import { ScheduledMaintenanceFeedEventType } from "../../Models/DatabaseModels/ScheduledMaintenanceFeed";
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 ScheduledMaintenanceLabelRuleEngineServiceClass {
    /**
     * Evaluates ScheduledMaintenanceLabelRule rows for the given event and
     * attaches matched labels to the event. Each matched rule contributes:
     *   - labels listed on `labelsToAdd`
     *   - all labels of the event's monitors when `inheritLabelsFromMonitors`
     *   - all labels of the event's hosts when `inheritLabelsFromHosts`
     *   - all labels of the event's Kubernetes clusters when `inheritLabelsFromKubernetesClusters`
     *   - all labels of the event's Docker hosts when `inheritLabelsFromDockerHosts`
     *   - all labels of the event's services when `inheritLabelsFromServices`
     * The union is deduped against labels already on the event before insert
     * to avoid PK conflicts on the ScheduledMaintenanceLabel join table.
     */
    async applyRulesToScheduledMaintenance(scheduledMaintenance) {
        var _a, _b, _c, _d, _e, _f, _g;
        if (!scheduledMaintenance.id || !scheduledMaintenance.projectId) {
            return;
        }
        try {
            const rules = await ScheduledMaintenanceLabelRuleService.findBy({
                query: {
                    projectId: scheduledMaintenance.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    monitors: { _id: true },
                    scheduledMaintenanceLabels: { _id: true },
                    monitorLabels: { _id: true },
                    titlePattern: true,
                    descriptionPattern: 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.doesScheduledMaintenanceMatchRule(scheduledMaintenance, 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 eventWithResources = null;
            if (needsRelatedResources) {
                eventWithResources = await ScheduledMaintenanceService.findOneById({
                    id: scheduledMaintenance.id,
                    select: {
                        hosts: { _id: true },
                        kubernetesClusters: { _id: true },
                        dockerHosts: { _id: true },
                        services: { _id: true },
                    },
                    props: { isRoot: true },
                });
            }
            if (inheritFromMonitors && ((_a = scheduledMaintenance.monitors) === null || _a === void 0 ? void 0 : _a.length)) {
                for (const eventMonitor of scheduledMaintenance.monitors) {
                    if (!eventMonitor.id) {
                        continue;
                    }
                    const monitor = await MonitorService.findOneById({
                        id: eventMonitor.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 = eventWithResources === null || eventWithResources === void 0 ? void 0 : eventWithResources.hosts) === null || _b === void 0 ? void 0 : _b.length)) {
                for (const eventHost of eventWithResources.hosts) {
                    if (!eventHost.id) {
                        continue;
                    }
                    const host = await HostService.findOneById({
                        id: eventHost.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 = eventWithResources === null || eventWithResources === void 0 ? void 0 : eventWithResources.kubernetesClusters) === null || _c === void 0 ? void 0 : _c.length)) {
                for (const eventCluster of eventWithResources.kubernetesClusters) {
                    if (!eventCluster.id) {
                        continue;
                    }
                    const cluster = await KubernetesClusterService.findOneById({
                        id: eventCluster.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 = eventWithResources === null || eventWithResources === void 0 ? void 0 : eventWithResources.dockerHosts) === null || _d === void 0 ? void 0 : _d.length)) {
                for (const eventDockerHost of eventWithResources.dockerHosts) {
                    if (!eventDockerHost.id) {
                        continue;
                    }
                    const dockerHost = await DockerHostService.findOneById({
                        id: eventDockerHost.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 = eventWithResources === null || eventWithResources === void 0 ? void 0 : eventWithResources.services) === null || _e === void 0 ? void 0 : _e.length)) {
                for (const eventService of eventWithResources.services) {
                    if (!eventService.id) {
                        continue;
                    }
                    const service = await ServiceService.findOneById({
                        id: eventService.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 eventWithLabels = await ScheduledMaintenanceService.findOneById({
                id: scheduledMaintenance.id,
                select: { labels: { _id: true } },
                props: { isRoot: true },
            });
            const existingLabelIds = new Set(((eventWithLabels === null || eventWithLabels === void 0 ? void 0 : eventWithLabels.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 ScheduledMaintenanceService.getRepository()
                .createQueryBuilder()
                .relation(ScheduledMaintenance, "labels")
                .of(scheduledMaintenance.id.toString())
                .add(newLabelIds);
            /*
             * Sync in-memory event.labels with the now-persisted set so any
             * downstream consumers in the same onCreateSuccess chain see the new
             * labels.
             */
            const mergedLabelIds = new Set([
                ...existingLabelIds,
                ...newLabelIds,
            ]);
            scheduledMaintenance.labels = Array.from(mergedLabelIds).map((id) => {
                const label = new Label();
                label.id = new ObjectID(id);
                return label;
            });
            logger.debug(`ScheduledMaintenanceLabelRuleEngine attached ${newLabelIds.length} labels to event ${scheduledMaintenance.id}`, {
                projectId: scheduledMaintenance.projectId.toString(),
            });
            await this.createRuleExecutedFeedItem({
                scheduledMaintenance,
                matchedRules,
                addedLabelIds: newLabelIds,
            });
        }
        catch (error) {
            logger.error(`Error applying scheduled maintenance label rules: ${error}`, {
                projectId: (_f = scheduledMaintenance.projectId) === null || _f === void 0 ? void 0 : _f.toString(),
                scheduledMaintenanceId: (_g = scheduledMaintenance.id) === null || _g === void 0 ? void 0 : _g.toString(),
            });
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { scheduledMaintenance, matchedRules, addedLabelIds } = data;
        if (!scheduledMaintenance.id ||
            !scheduledMaintenance.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 = `🏷️ **Scheduled Maintenance Label Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAdded the following label${labelNames.length === 1 ? "" : "s"} to the event:${labelsPart}`;
            await ScheduledMaintenanceFeedService.createScheduledMaintenanceFeedItem({
                scheduledMaintenanceId: scheduledMaintenance.id,
                projectId: scheduledMaintenance.projectId,
                scheduledMaintenanceFeedEventType: ScheduledMaintenanceFeedEventType.LabelRuleExecuted,
                displayColor: Indigo500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`ScheduledMaintenanceLabelRuleEngine: failed to create rule-executed feed item: ${error instanceof Error ? error.message : String(error)}`, {
                projectId: (_a = scheduledMaintenance.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                scheduledMaintenanceId: (_b = scheduledMaintenance.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    async doesScheduledMaintenanceMatchRule(scheduledMaintenance, rule) {
        if (rule.monitors && rule.monitors.length > 0) {
            if (!scheduledMaintenance.monitors ||
                scheduledMaintenance.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 eventMonitorIds = scheduledMaintenance.monitors.map((m) => {
                var _a;
                return ((_a = m.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleMonitorIds.some((id) => {
                return eventMonitorIds.includes(id);
            })) {
                return false;
            }
        }
        if (rule.scheduledMaintenanceLabels &&
            rule.scheduledMaintenanceLabels.length > 0) {
            if (!scheduledMaintenance.labels ||
                scheduledMaintenance.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.scheduledMaintenanceLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const eventLabelIds = scheduledMaintenance.labels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleLabelIds.some((id) => {
                return eventLabelIds.includes(id);
            })) {
                return false;
            }
        }
        const hasMonitorCriteria = Boolean((rule.monitorLabels && rule.monitorLabels.length > 0) ||
            rule.monitorNamePattern ||
            rule.monitorDescriptionPattern);
        if (hasMonitorCriteria) {
            if (!scheduledMaintenance.monitors ||
                scheduledMaintenance.monitors.length === 0) {
                return false;
            }
            let anyMonitorMatches = false;
            for (const eventMonitor of scheduledMaintenance.monitors) {
                if (!eventMonitor.id) {
                    continue;
                }
                const monitor = await MonitorService.findOneById({
                    id: eventMonitor.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.titlePattern &&
            (!scheduledMaintenance.title ||
                !this.testRegex(rule.titlePattern, scheduledMaintenance.title, rule))) {
            return false;
        }
        if (rule.descriptionPattern &&
            (!scheduledMaintenance.description ||
                !this.testRegex(rule.descriptionPattern, scheduledMaintenance.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 scheduled maintenance label rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ScheduledMaintenance]),
    __metadata("design:returntype", Promise)
], ScheduledMaintenanceLabelRuleEngineServiceClass.prototype, "applyRulesToScheduledMaintenance", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], ScheduledMaintenanceLabelRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ScheduledMaintenance,
        ScheduledMaintenanceLabelRule]),
    __metadata("design:returntype", Promise)
], ScheduledMaintenanceLabelRuleEngineServiceClass.prototype, "doesScheduledMaintenanceMatchRule", null);
export default new ScheduledMaintenanceLabelRuleEngineServiceClass();
//# sourceMappingURL=ScheduledMaintenanceLabelRuleEngineService.js.map