/**
 * Type keyword capitalization validator for Acurity Architect.
 * Validates that type keywords (STRING, SHORT, LONG, DOUBLE, BOOLEAN, DATE, etc.)
 * are capitalised when they appear after a colon in VAR and FUNCTION declarations.
 * Uses the token stream so hash-mode output lines and string literals
 * are naturally excluded from the check.
 */

import { TokenType } from "../lexer/tokenTypes.js";
import { buildDocumentAst } from "../ast/documentAst.js";
import { createDiagnostic } from "../diagnostics/diagnosticFactory.js";

/**
 * Validates that type keywords are capitalized in a document.
 * @param {object} document - The document to validate
 * @param {Function} getRuleSeverity
 * @param {object} [options]
 * @param {object[]} [options.executionClassificationMap] - Per-line execution classification
 * @returns {object[]} - Array of type keyword capitalization diagnostics
 */
function validateTypeKeywordCapitalization(document, getRuleSeverity, options = {}) {
    const diagnostics = [];
    const { tokens } = buildDocumentAst(document);
    const ecm = options.executionClassificationMap || null;

    // Build a list of tokens that carry meaning (skip whitespace, newlines, comments,
    // and tokens on output or non-executable lines).
    // This lets us check "is the immediately preceding token a COLON?" cleanly.
    const meaningful = tokens.filter(t => {
        if (t.type === TokenType.WHITESPACE || t.type === TokenType.NEWLINE || t.type === TokenType.COMMENT) return false;
        if (ecm) {
            const cls = ecm[t.line];
            if (cls && (cls.isOutput || !cls.isExecutable)) return false;
        }
        return true;
    });

    for (let i = 0; i < meaningful.length; i++) {
        const token = meaningful[i];
        if (token.type !== TokenType.TYPE_KEYWORD) continue;

        // Only flag type keywords that follow a colon (declaration context).
        const prev = meaningful[i - 1];
        if (!prev || prev.type !== TokenType.COLON) continue;

        // Already uppercase — no issue.
        if (token.value === token.value.toUpperCase()) continue;

        const range = {
            start: { line: token.line, character: token.char },
            end:   { line: token.line, character: token.char + token.value.length }
        };
        const diag = createDiagnostic(
            range,
            { messageId: "ACU-TYPE-001", params: { keyword: token.value, uppercase: token.value.toUpperCase() } },
            getRuleSeverity
        );
        if (diag) diagnostics.push(diag);
    }

    return diagnostics;
}

export {
    validateTypeKeywordCapitalization
};
