/**
 * Helpers for reading VS Code settings contributions from package.json.
 * Used by generate-diagnostic-docs.js and validate-settings-registration.js
 * to map rule IDs to their contributed setting keys.
 */

import { createRequire } from "module";

const _require = createRequire(import.meta.url);
const packageJson = _require("../../package.json");

const RULE_SETTING_KEY_PATTERN = /^acurity\.rules\.(core|standards)\.([A-Za-z0-9]+)\.severity$/;

function getConfigurationSections() {
    return packageJson?.contributes?.configuration || [];
}

function getContributedSettingKeys() {
    const sections = getConfigurationSections();
    const keys = [];
    for (const section of sections) {
        for (const key of Object.keys(section.properties || {})) {
            keys.push(key);
        }
    }
    return keys;
}

function getRuleSettingRows() {
    const sections = getConfigurationSections();
    const rows = [];
    for (const section of sections) {
        const sectionTitle = section.title || "";
        for (const key of Object.keys(section.properties || {})) {
            const match = key.match(RULE_SETTING_KEY_PATTERN);
            if (!match) {
                continue;
            }
            rows.push({
                key,
                group: match[1],
                ruleId: match[2],
                sectionTitle
            });
        }
    }
    rows.sort((a, b) => a.key.localeCompare(b.key));
    return rows;
}

function getRuleSettingKeyByRuleId() {
    const mapping = {};
    for (const row of getRuleSettingRows()) {
        mapping[row.ruleId] = row.key;
    }
    return mapping;
}

export {
    getContributedSettingKeys,
    getConfigurationSections,
    getRuleSettingKeyByRuleId,
    getRuleSettingRows,
    RULE_SETTING_KEY_PATTERN
};
