"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reconcileAppsResolutionIssuesToProblems = reconcileAppsResolutionIssuesToProblems;
const time_1 = require("@longrun-ai/kernel/utils/time");
const problems_1 = require("../problems");
const APPS_PROBLEM_PREFIX = 'apps/apps_resolution/';
function sanitizeProblemIdSegment(segment) {
    return segment.replace(/[^a-zA-Z0-9_-]/g, '_');
}
function asNonEmptyString(v) {
    if (typeof v !== 'string')
        return null;
    const trimmed = v.trim();
    return trimmed === '' ? null : trimmed;
}
function buildAppsIssueProblemId(issue) {
    const kindSeg = sanitizeProblemIdSegment(issue.kind);
    const appId = asNonEmptyString(issue.detail['appId']);
    const depId = asNonEmptyString(issue.detail['dependencyId']);
    if (appId && depId) {
        return `${APPS_PROBLEM_PREFIX}${kindSeg}/${sanitizeProblemIdSegment(appId)}/${sanitizeProblemIdSegment(depId)}`;
    }
    if (appId) {
        return `${APPS_PROBLEM_PREFIX}${kindSeg}/${sanitizeProblemIdSegment(appId)}`;
    }
    return `${APPS_PROBLEM_PREFIX}${kindSeg}`;
}
function reconcileAppsResolutionIssuesToProblems(params) {
    const now = (0, time_1.formatUnifiedTimestamp)(new Date());
    const desired = [];
    for (const issue of params.issues) {
        desired.push({
            kind: 'generic_problem',
            source: 'system',
            id: buildAppsIssueProblemId(issue),
            severity: issue.severity,
            timestamp: now,
            message: issue.message,
            detail: { text: JSON.stringify(issue.detail, null, 2) },
        });
    }
    (0, problems_1.reconcileProblemsByPrefix)(APPS_PROBLEM_PREFIX, desired);
}
