/**
 * Completion context helpers for Acurity Architect.
 * Pure module — no VS Code dependency.
 */

const BLOCK_CLOSER_RE = /\b(ENDIF|ENDDO|ENDCASE|ENDFUNCTION)\b/i;

/**
 * Keywords that introduce an expression context on the same line (no `=` needed).
 * E.g. `IF GET_TOK` — cursor is inside the IF condition, not at statement start.
 * The `#?` covers HASH-ON prefixed lines like `#IF GET_TOK`.
 */
const EXPRESSION_OPENER_RE = /^\s*#?\s*(IF|CASE|UNTIL|RETURN|VALUE|DO\s+WHILE)\s+/i;

/**
 * Returns true if the cursor (end of linePrefix) is at statement start:
 * - The line does not start with an expression-opening keyword (IF, CASE, UNTIL, etc.)
 * - No assignment operator `=` has been typed on this line
 * - The cursor is not inside open parentheses
 *
 * @param {string} linePrefix  Text from column 0 to the cursor position.
 * @returns {boolean}
 */
function isStatementStart(linePrefix) {
    if (EXPRESSION_OPENER_RE.test(linePrefix)) return false;
    const trimmed = linePrefix.trimStart();
    if (trimmed.includes("=")) return false;
    let depth = 0;
    for (const ch of trimmed) {
        if (ch === "(") depth++;
        else if (ch === ")") depth = Math.max(0, depth - 1);
    }
    return depth === 0;
}

/**
 * Returns true if the line prefix already contains a block-closing keyword
 * (ENDIF, ENDDO, ENDCASE, ENDFUNCTION). Nothing valid may follow these on
 * the same line (other than a trailing comment).
 *
 * @param {string} linePrefix
 * @returns {boolean}
 */
function isAfterBlockCloser(linePrefix) {
    return BLOCK_CLOSER_RE.test(linePrefix);
}

export { isStatementStart, isAfterBlockCloser };
