"use strict";
/*
 * Copyright OpenSearch Contributors
 * SPDX-License-Identifier: Apache-2.0
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.mergeConfig = mergeConfig;
exports.runLint = runLint;
const catalog_1 = require("./catalog");
const detector_registry_1 = require("./detector_registry");
const version_filter_1 = require("./version_filter");
function mergeConfig(local, override) {
    if (!override) {
        return local;
    }
    return {
        ...local,
        ...override,
        appliesTo: { ...local.appliesTo, ...(override.appliesTo ?? {}) },
    };
}
function isContextEmpty(context) {
    return ((!context?.fields || context.fields.size === 0) &&
        (!context?.visibleIndices || context.visibleIndices.length === 0));
}
function runLint(tree, options) {
    const { catalog = (0, catalog_1.getBundledCatalog)(), bundleOverrides, dataSourceVersion, ruleNameToIndex, context, knownVersion = version_filter_1.OSD_KNOWN_VERSION, } = options;
    const diagnostics = [];
    const effectiveOverrides = bundleOverrides ?? context?.overrides;
    for (const localConfig of catalog) {
        const config = mergeConfig(localConfig, effectiveOverrides?.[localConfig.id]);
        if (!config.enabled ||
            config.needsExplain ||
            (config.runtimeOnly && context?.grammarSurface !== 'runtime-bundle') ||
            !(0, version_filter_1.appliesTo)(config, dataSourceVersion, context?.isCalcite, knownVersion) ||
            (config.needsContext && isContextEmpty(context))) {
            continue;
        }
        const detector = (0, detector_registry_1.getDetector)(config.detector);
        if (!detector) {
            // eslint-disable-next-line no-console
            console.warn(`[ppl-lint] inert rule: no detector registered for "${config.id}"`);
            continue;
        }
        try {
            const ruleDiagnostics = detector(tree, config, context ?? {}, ruleNameToIndex);
            diagnostics.push(...ruleDiagnostics);
        }
        catch (e) {
            // eslint-disable-next-line no-console
            console.warn(`[ppl-lint] rule "${config.id}" threw and was skipped`, e);
        }
    }
    return diagnostics;
}
//# sourceMappingURL=lint_runner.js.map