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 AlertService from "../../Services/AlertService";
import AlertStateTimelineService from "../../Services/AlertStateTimelineService";
import AlertInternalNoteService from "../../Services/AlertInternalNoteService";
import CaptureSpan from "../Telemetry/CaptureSpan";
import OneUptimeDate from "../../../Types/Date";
import SortOrder from "../../../Types/BaseDatabase/SortOrder";
export default class AlertAIContextBuilder {
    static async buildAlertContext(data) {
        const alert = await AlertService.findOneById({
            id: data.alertId,
            select: {
                _id: true,
                title: true,
                description: true,
                createdAt: true,
                customFields: true,
                projectId: true,
                alertSeverity: {
                    name: true,
                    color: true,
                },
                currentAlertState: {
                    name: true,
                    color: true,
                },
                monitor: {
                    name: true,
                },
                labels: {
                    name: true,
                    color: true,
                },
                rootCause: true,
                remediationNotes: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!alert) {
            throw new Error("Alert not found");
        }
        // Fetch state timeline
        const stateTimeline = await AlertStateTimelineService.findBy({
            query: {
                alertId: data.alertId,
            },
            select: {
                _id: true,
                createdAt: true,
                startsAt: true,
                endsAt: true,
                rootCause: true,
                alertState: {
                    name: true,
                    color: true,
                },
                createdByUser: {
                    name: true,
                    email: true,
                },
            },
            sort: {
                startsAt: SortOrder.Ascending,
            },
            limit: 100,
            skip: 0,
            props: {
                isRoot: true,
            },
        });
        // Fetch internal notes
        const internalNotes = await AlertInternalNoteService.findBy({
            query: {
                alertId: data.alertId,
            },
            select: {
                _id: true,
                note: true,
                createdAt: true,
                createdByUser: {
                    name: true,
                    email: true,
                },
            },
            sort: {
                createdAt: SortOrder.Ascending,
            },
            limit: 100,
            skip: 0,
            props: {
                isRoot: true,
            },
        });
        return {
            alert,
            stateTimeline,
            internalNotes,
        };
    }
    static formatAlertContextForNote(contextData, template) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
        const { alert, stateTimeline, internalNotes } = contextData;
        let contextText = "";
        // Basic alert information
        contextText += "# Alert Information\n\n";
        contextText += `**Title:** ${alert.title || "N/A"}\n\n`;
        contextText += `**Description:** ${alert.description || "N/A"}\n\n`;
        contextText += `**Severity:** ${((_a = alert.alertSeverity) === null || _a === void 0 ? void 0 : _a.name) || "N/A"}\n\n`;
        contextText += `**Current State:** ${((_b = alert.currentAlertState) === null || _b === void 0 ? void 0 : _b.name) || "N/A"}\n\n`;
        contextText += `**Created At:** ${alert.createdAt ? OneUptimeDate.getDateAsFormattedString(alert.createdAt) : "N/A"}\n\n`;
        // Affected monitor
        if (alert.monitor) {
            contextText += `**Monitor:** ${alert.monitor.name || "N/A"}\n\n`;
        }
        // Labels
        if (alert.labels && alert.labels.length > 0) {
            contextText += "**Labels:** ";
            contextText += alert.labels
                .map((l) => {
                return l.name;
            })
                .join(", ");
            contextText += "\n\n";
        }
        // Root cause if available
        if (alert.rootCause) {
            contextText += `**Root Cause:** ${alert.rootCause}\n\n`;
        }
        // Remediation notes if available
        if (alert.remediationNotes) {
            contextText += `**Remediation Notes:** ${alert.remediationNotes}\n\n`;
        }
        // State timeline
        if (stateTimeline.length > 0) {
            contextText += "# State Timeline\n\n";
            for (const timeline of stateTimeline) {
                const startTime = timeline.startsAt
                    ? OneUptimeDate.getDateAsFormattedString(timeline.startsAt)
                    : "N/A";
                const stateName = ((_d = (_c = timeline.alertState) === null || _c === void 0 ? void 0 : _c.name) === null || _d === void 0 ? void 0 : _d.toString()) || "Unknown";
                const createdBy = ((_f = (_e = timeline.createdByUser) === null || _e === void 0 ? void 0 : _e.name) === null || _f === void 0 ? void 0 : _f.toString()) ||
                    ((_h = (_g = timeline.createdByUser) === null || _g === void 0 ? void 0 : _g.email) === null || _h === void 0 ? void 0 : _h.toString()) ||
                    "System";
                contextText += `- **${startTime}**: State changed to **${stateName}** by ${createdBy}\n`;
                if (timeline.rootCause) {
                    contextText += `  - Root cause noted: ${timeline.rootCause}\n`;
                }
            }
            contextText += "\n";
        }
        // Internal notes
        if (internalNotes.length > 0) {
            contextText += "# Internal Notes (Private)\n\n";
            for (const note of internalNotes) {
                const noteTime = note.createdAt
                    ? OneUptimeDate.getDateAsFormattedString(note.createdAt)
                    : "N/A";
                const createdBy = ((_k = (_j = note.createdByUser) === null || _j === void 0 ? void 0 : _j.name) === null || _k === void 0 ? void 0 : _k.toString()) ||
                    ((_m = (_l = note.createdByUser) === null || _l === void 0 ? void 0 : _l.email) === null || _m === void 0 ? void 0 : _m.toString()) ||
                    "Unknown";
                contextText += `**[${noteTime}] ${createdBy}:**\n`;
                contextText += `${note.note || "N/A"}\n\n`;
            }
        }
        // System prompt for note generation (alerts only have internal notes)
        let systemPrompt;
        if (template) {
            systemPrompt = `You are an expert Site Reliability Engineer (SRE). Your task is to fill in an internal alert note template based on the provided alert data.

CRITICAL INSTRUCTIONS:
- You MUST use ONLY the exact template structure provided below
- Fill in each section of the template with relevant information from the alert data
- Do NOT add any new sections, headers, or content that is not part of the template
- Do NOT add introductions, conclusions, or any text outside the template structure
- Be technical and detailed - this is for the internal team
- Include relevant technical details, observations, and analysis

TEMPLATE TO FILL (use this exact structure):

${template}`;
        }
        else {
            systemPrompt = `You are an expert Site Reliability Engineer (SRE). Your task is to generate an internal alert note for the team.

The note should:
1. Provide technical details about the alert and its current status
2. Document observations, findings, or actions taken
3. Include relevant metrics or error messages if mentioned in the context
4. Be detailed enough to help team members understand the situation
5. Use technical language appropriate for the engineering team

Write in markdown format for better readability. Be thorough and technical.`;
        }
        // Build user message
        const userMessage = template
            ? `Fill in the template above using ONLY the following alert data. Output only the filled template, nothing else:\n\n${contextText}`
            : `Based on the following alert data, please generate an internal technical alert note:\n\n${contextText}`;
        // Build messages array
        const messages = [
            {
                role: "system",
                content: systemPrompt,
            },
            {
                role: "user",
                content: userMessage,
            },
        ];
        return {
            contextText,
            systemPrompt,
            messages,
        };
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], AlertAIContextBuilder, "buildAlertContext", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, String]),
    __metadata("design:returntype", Object)
], AlertAIContextBuilder, "formatAlertContextForNote", null);
//# sourceMappingURL=AlertAIContextBuilder.js.map