/**
 * Generates diagnostic catalog documentation in README.md.
 */

import * as fs from "fs";
import * as path from "path";
import { fileURLToPath } from "url";
import {
    DIAGNOSTIC_CATALOG,
    getProfileRuleSeverities
} from "../core/src/diagnostics/diagnosticCatalog.js";
import { getRuleSettingKeyByRuleId } from "./shared/settings-metadata.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const START_MARKER = "<!-- DIAGNOSTIC_CATALOG_TABLE_START -->";
const END_MARKER = "<!-- DIAGNOSTIC_CATALOG_TABLE_END -->";

function escapeCell(text) {
    return String(text).replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
}

function buildTable() {
    const defaultProfile = getProfileRuleSeverities("default");
    const rows = Object.entries(DIAGNOSTIC_CATALOG)
        .sort(([a], [b]) => a.localeCompare(b))
        .map(([id, entry]) => {
            const params = (entry.paramKeys || []).length > 0 ? entry.paramKeys.join(", ") : "-";
            const defaultSeverity = defaultProfile[entry.ruleId] || "warning";
            const category = entry.category || "-";
            return `| \`${id}\` | ${entry.ruleId} | ${category} | ${defaultSeverity} | ${escapeCell(entry.message)} | ${escapeCell(params)} |`;
        });

    return [
        "| Message ID | Rule | Category | Default Severity | Message | Params |",
        "| --- | --- | --- | --- | --- | --- |",
        ...rows
    ].join("\n");
}

function buildSection() {
    const table = buildTable();
    return [
        "## Diagnostic Catalog",
        "",
        "This section is auto-generated from `src/diagnostics/diagnosticCatalog.js` during build/packaging.",
        "",
        "### Concepts",
        "",
        "Two distinct entities appear in this table:",
        "",
        "- **Message** — a specific diagnostic instance with a stable `ACU-XXX-NNN` ID.",
        "  Used in VS Code hover tooltips, the Problems panel, and suppression comments",
        "  (`// @rule-ignore ACU-INT-001`). Multiple messages can belong to one Rule.",
        "- **Rule** — a named validation behaviour (camelCase key). Controls a single VS Code",
        "  setting (`acurity.rules.<group>.<Rule>.severity`). One Rule may produce several",
        "  distinct Message types.",
        "",
        START_MARKER,
        table,
        END_MARKER,
        ""
    ].join("\n");
}

function generateDiagnosticDocs(readmePath) {
    const resolvedReadme = readmePath || path.join(__dirname, "..", "README.md");
    const section = buildSection();

    let readmeText = fs.readFileSync(resolvedReadme, "utf8");
    const startIdx = readmeText.indexOf(START_MARKER);
    const endIdx = readmeText.indexOf(END_MARKER);

    if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
        const before = readmeText.slice(0, startIdx);
        const after = readmeText.slice(endIdx + END_MARKER.length);
        const replacement = `${START_MARKER}\n${buildTable()}\n${END_MARKER}`;
        readmeText = `${before}${replacement}${after}`;
    } else {
        if (!readmeText.endsWith("\n")) {
            readmeText += "\n";
        }
        readmeText += `\n${section}`;
    }

    fs.writeFileSync(resolvedReadme, readmeText);
    return resolvedReadme;
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
    const outPath = generateDiagnosticDocs();
    console.log(`Generated diagnostic catalog docs in ${outPath}`);
}

export {
    generateDiagnosticDocs
};
