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 Monitor from "../../Models/DatabaseModels/Monitor";
import LabelService from "./LabelService";
import MonitorFeedService from "./MonitorFeedService";
import MonitorLabelRuleService from "./MonitorLabelRuleService";
import MonitorService from "./MonitorService";
import { MonitorFeedEventType } from "../../Models/DatabaseModels/MonitorFeed";
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 MonitorLabelRuleEngineServiceClass {
    /**
     * Evaluates MonitorLabelRule rows for the given monitor and attaches matched
     * labels to it. The union is deduped against labels already on the monitor
     * before insert to avoid PK conflicts on the MonitorLabel join table.
     */
    async applyRulesToMonitor(monitor) {
        var _a, _b;
        if (!monitor.id || !monitor.projectId) {
            return;
        }
        try {
            const rules = await MonitorLabelRuleService.findBy({
                query: {
                    projectId: monitor.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    monitorLabels: { _id: true },
                    monitorNamePattern: true,
                    monitorDescriptionPattern: true,
                    labelsToAdd: { _id: true },
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const monitorWithDetails = await MonitorService.findOneById({
                id: monitor.id,
                select: {
                    name: true,
                    description: true,
                    labels: { _id: true },
                },
                props: { isRoot: true },
            });
            if (!monitorWithDetails) {
                return;
            }
            const labelIdsToAdd = new Set();
            const matchedRules = [];
            for (const rule of rules) {
                const matches = this.doesMonitorMatchRule(monitorWithDetails, rule);
                if (!matches) {
                    continue;
                }
                matchedRules.push(rule);
                for (const label of rule.labelsToAdd || []) {
                    if (label.id) {
                        labelIdsToAdd.add(label.id.toString());
                    }
                }
            }
            if (labelIdsToAdd.size === 0) {
                return;
            }
            const existingLabelIds = new Set((monitorWithDetails.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 MonitorService.getRepository()
                .createQueryBuilder()
                .relation(Monitor, "labels")
                .of(monitor.id.toString())
                .add(newLabelIds);
            /*
             * Sync in-memory monitor.labels with the now-persisted set so a downstream
             * owner-rule engine in the same onCreateSuccess chain can match on
             * rule-added labels.
             */
            const mergedLabelIds = new Set([
                ...existingLabelIds,
                ...newLabelIds,
            ]);
            monitor.labels = Array.from(mergedLabelIds).map((id) => {
                const label = new Label();
                label.id = new ObjectID(id);
                return label;
            });
            logger.debug(`MonitorLabelRuleEngine attached ${newLabelIds.length} labels to monitor ${monitor.id}`, { projectId: monitor.projectId.toString() });
            await this.createRuleExecutedFeedItem({
                monitor,
                matchedRules,
                addedLabelIds: newLabelIds,
            });
        }
        catch (error) {
            logger.error(`Error applying monitor label rules: ${error}`, {
                projectId: (_a = monitor.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                monitorId: (_b = monitor.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { monitor, matchedRules, addedLabelIds } = data;
        if (!monitor.id ||
            !monitor.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 = `🏷️ **Monitor Label Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAdded the following label${labelNames.length === 1 ? "" : "s"} to the monitor:${labelsPart}`;
            await MonitorFeedService.createMonitorFeedItem({
                monitorId: monitor.id,
                projectId: monitor.projectId,
                monitorFeedEventType: MonitorFeedEventType.LabelRuleExecuted,
                displayColor: Indigo500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`MonitorLabelRuleEngine: failed to create rule-executed feed item: ${error instanceof Error ? error.message : String(error)}`, {
                projectId: (_a = monitor.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                monitorId: (_b = monitor.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    doesMonitorMatchRule(monitor, rule) {
        if (rule.monitorLabels && rule.monitorLabels.length > 0) {
            if (!monitor.labels || monitor.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = 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 (!ruleLabelIds.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;
        }
        return true;
    }
    testRegex(pattern, value, rule) {
        try {
            const regex = new RegExp(pattern, "i");
            return regex.test(value);
        }
        catch (_a) {
            logger.warn(`Invalid regex in monitor label rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Monitor]),
    __metadata("design:returntype", Promise)
], MonitorLabelRuleEngineServiceClass.prototype, "applyRulesToMonitor", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MonitorLabelRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
export default new MonitorLabelRuleEngineServiceClass();
//# sourceMappingURL=MonitorLabelRuleEngineService.js.map