/**
 * Block context analysis for Acurity Architect.
 * Computes the open-block stack and hash mode at a given cursor line.
 * Pure module — no VS Code dependency.
 */

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

const BLOCK_OPENERS = new Set(["IF", "DO", "CASE", "FUNCTION"]);
const BLOCK_CLOSERS = new Set(["ENDIF", "ENDDO", "ENDCASE", "ENDFUNCTION"]);

/**
 * Returns the block stack and hash mode at `cursorLineIndex`.
 * Tokens on the cursor line itself are not yet in scope.
 *
 * Stack is innermost-last: `stack[stack.length - 1]` is the deepest open block.
 *
 * @param {object} document  VS Code TextDocument (or plain {lineCount, lineAt, getText, uri, version})
 * @param {number} cursorLineIndex  0-based
 * @returns {{ stack: Array<{kind: string, lineIndex: number}>, hashMode: "on"|"off" }}
 */
function getBlockContextAtLine(document, cursorLineIndex) {
    const { tokens } = buildDocumentAst(document);
    const stack = [];
    let hashMode = "on";

    for (const token of tokens) {
        if (token.line >= cursorLineIndex) break;
        if (token.type !== TokenType.KEYWORD) continue;

        const keyword = token.value.toUpperCase();

        if (keyword === "HASH-ON")  { hashMode = "on";  continue; }
        if (keyword === "HASH-OFF") { hashMode = "off"; continue; }

        if (BLOCK_OPENERS.has(keyword)) {
            stack.push({ kind: keyword, lineIndex: token.line });
            continue;
        }

        if (BLOCK_CLOSERS.has(keyword) && stack.length > 0) {
            stack.pop();
        }
    }

    return { stack, hashMode };
}

export { getBlockContextAtLine };
