import { getCatalogEntry } from "./diagnosticCatalog.js";

/**
 * Creates a diagnostic from an ID and parameter payload.
 *
 * Usage:
 *   createDiagnostic(range, { messageId: "ACU-INT-001", params: { variableName: "x" } }, getRuleSeverity)
 */
function createDiagnostic(range, config, getRuleSeverity) {
    if (!config || typeof config !== "object" || !config.messageId || Array.isArray(config)) {
        throw new Error("createDiagnostic requires a config object with messageId and optional params.");
    }

    const entry = getCatalogEntry(config.messageId);
    if (!entry) {
        throw new Error(`Unknown messageId: ${config.messageId}`);
    }

    const ruleId = entry.ruleId;
    const message = renderMessage(entry.message, config.params || {});

    const severity = getRuleSeverity(ruleId);
    if (severity === null) {
        return null;
    }

    const diagnostic = {
        range,
        message,
        severity,
        code: config.messageId,
        source: "acurity",
        data: {
            messageId: config.messageId,
            params: config.params || null,
            ruleId
        }
    };

    return diagnostic;
}

/**
 * Renders a message template by interpolating parameters.
 * @param {string} template - Message template with {paramName} placeholders
 * @param {Object} params - Parameter values
 * @returns {string} - Rendered message
 */
function renderMessage(template, params = {}) {
    let result = template;
    for (const [key, value] of Object.entries(params)) {
        result = result.split(`{${key}}`).join(String(value));
    }
    return result;
}

export {
    createDiagnostic,
    renderMessage
};
