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 IncidentEpisode from "../../Models/DatabaseModels/IncidentEpisode";
import IncidentEpisodeFeedService from "./IncidentEpisodeFeedService";
import IncidentEpisodeLabelRuleService from "./IncidentEpisodeLabelRuleService";
import IncidentEpisodeService from "./IncidentEpisodeService";
import LabelService from "./LabelService";
import { IncidentEpisodeFeedEventType } from "../../Models/DatabaseModels/IncidentEpisodeFeed";
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 IncidentEpisodeLabelRuleEngineServiceClass {
    /**
     * Evaluates IncidentEpisodeLabelRule rows for the given episode and
     * attaches matched labels via the IncidentEpisodeLabel join table.
     * The union is deduped against the episode's existing labels first to
     * avoid PK conflicts on insert.
     */
    async applyRulesToEpisode(episode) {
        var _a, _b;
        if (!episode.id || !episode.projectId) {
            return;
        }
        try {
            const rules = await IncidentEpisodeLabelRuleService.findBy({
                query: {
                    projectId: episode.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    incidentSeverities: { _id: true },
                    episodeLabels: { _id: true },
                    episodeTitlePattern: true,
                    episodeDescriptionPattern: true,
                    labelsToAdd: { _id: true },
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const labelIdsToAdd = new Set();
            const matchedRules = [];
            for (const rule of rules) {
                if (!this.doesEpisodeMatchRule(episode, rule)) {
                    continue;
                }
                matchedRules.push(rule);
                for (const label of rule.labelsToAdd || []) {
                    if (label.id) {
                        labelIdsToAdd.add(label.id.toString());
                    }
                }
            }
            if (labelIdsToAdd.size === 0) {
                return;
            }
            const episodeWithLabels = await IncidentEpisodeService.findOneById({
                id: episode.id,
                select: { labels: { _id: true } },
                props: { isRoot: true },
            });
            const existingLabelIds = new Set(((episodeWithLabels === null || episodeWithLabels === void 0 ? void 0 : episodeWithLabels.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 IncidentEpisodeService.getRepository()
                .createQueryBuilder()
                .relation(IncidentEpisode, "labels")
                .of(episode.id.toString())
                .add(newLabelIds);
            logger.debug(`IncidentEpisodeLabelRuleEngine attached ${newLabelIds.length} labels to episode ${episode.id}`, { projectId: episode.projectId.toString() });
            await this.createRuleExecutedFeedItem({
                episode,
                matchedRules,
                addedLabelIds: newLabelIds,
            });
        }
        catch (error) {
            logger.error(`Error applying incident episode label rules: ${error}`, {
                projectId: (_a = episode.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                incidentEpisodeId: (_b = episode.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { episode, matchedRules, addedLabelIds } = data;
        if (!episode.id ||
            !episode.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 Episode Label Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAdded the following label${labelNames.length === 1 ? "" : "s"} to the episode:${labelsPart}`;
            await IncidentEpisodeFeedService.createIncidentEpisodeFeedItem({
                incidentEpisodeId: episode.id,
                projectId: episode.projectId,
                incidentEpisodeFeedEventType: IncidentEpisodeFeedEventType.LabelRuleExecuted,
                displayColor: Indigo500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`IncidentEpisodeLabelRuleEngine: failed to create rule-executed feed item: ${error instanceof Error ? error.message : String(error)}`, {
                projectId: (_a = episode.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                incidentEpisodeId: (_b = episode.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    doesEpisodeMatchRule(episode, rule) {
        if (rule.incidentSeverities && rule.incidentSeverities.length > 0) {
            if (!episode.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(episode.incidentSeverityId.toString())) {
                return false;
            }
        }
        if (rule.episodeLabels && rule.episodeLabels.length > 0) {
            if (!episode.labels || episode.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.episodeLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const episodeLabelIds = episode.labels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleLabelIds.some((id) => {
                return episodeLabelIds.includes(id);
            })) {
                return false;
            }
        }
        if (rule.episodeTitlePattern &&
            (!episode.title ||
                !this.testRegex(rule.episodeTitlePattern, episode.title, rule))) {
            return false;
        }
        if (rule.episodeDescriptionPattern &&
            (!episode.description ||
                !this.testRegex(rule.episodeDescriptionPattern, episode.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 episode label rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [IncidentEpisode]),
    __metadata("design:returntype", Promise)
], IncidentEpisodeLabelRuleEngineServiceClass.prototype, "applyRulesToEpisode", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], IncidentEpisodeLabelRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
export default new IncidentEpisodeLabelRuleEngineServiceClass();
//# sourceMappingURL=IncidentEpisodeLabelRuleEngineService.js.map