import { arrayFirst } from "ts-extras";
import { ruleCreator } from "../_internal/rule-creator.js";
const isEslintDirectiveComment = (comment) => comment.type === "Block" && comment.value.trimStart().startsWith("eslint-");
const expectedBlankLines = (comment) => {
    if (comment.type === "Line" || isEslintDirectiveComment(comment)) {
        return 0;
    }
    return /\r\n|\n/u.test(comment.value) ? 1 : 0;
};
const buildFix = (sourceCode, comment, nextNode, expected) => (fixer) => {
    const textBetween = sourceCode.text.slice(comment.range[1], arrayFirst(nextNode.range));
    const lineEnding = textBetween.includes("\r\n") ? "\r\n" : "\n";
    const indentation = " ".repeat(nextNode.loc.start.column);
    return fixer.replaceTextRange([comment.range[1], arrayFirst(nextNode.range)], `${lineEnding.repeat(expected + 1)}${indentation}`);
};
/**
 * Enforce consistent blank-line spacing after comments.
 */
const rule = ruleCreator({
    create: (context) => ({
        Program: () => {
            const comments = context.sourceCode.getAllComments();
            for (const comment of comments) {
                const nextNode = context.sourceCode.getTokenAfter(comment, {
                    includeComments: false,
                });
                if (nextNode === null) {
                    continue;
                }
                const blankLines = nextNode.loc.start.line - comment.loc.end.line - 1;
                const expected = expectedBlankLines(comment);
                if (blankLines === expected) {
                    continue;
                }
                context.report({
                    fix: buildFix(context.sourceCode, comment, nextNode, expected),
                    messageId: "invalidSpacing",
                    node: comment,
                });
            }
        },
    }),
    defaultOptions: [],
    meta: {
        deprecated: false,
        docs: {
            deprecated: false,
            description: "enforce consistent blank-line spacing after comments.",
            frozen: false,
            recommended: false,
            url: "https://nick2bad4u.github.io/eslint-plugin-etc-misc/docs/rules/comment-spacing",
        },
        fixable: "whitespace",
        hasSuggestions: false,
        messages: {
            invalidSpacing: "Incorrect blank-line spacing after this comment.",
        },
        schema: [],
        type: "layout",
    },
    name: "comment-spacing",
});
export default rule;
//# sourceMappingURL=comment-spacing.js.map