import { loadNativeSearchBinding } from "./search-native.js";
const PURE_CLOSER_RE = /^[)\]}]+[;,]?\s*$/;
/** Strip line comments and same-line string literals so delimiters inside them are not counted. */
function stripNonCode(line) {
    let out = "";
    let quote = "";
    for (let i = 0; i < line.length; i++) {
        const ch = line[i];
        if (quote) {
            if (ch === "\\") {
                i++;
                continue;
            }
            if (ch === quote)
                quote = "";
            continue;
        }
        if (ch === '"' || ch === "'" || ch === "`") {
            quote = ch;
            continue;
        }
        if (ch === "/" && line[i + 1] === "/")
            break;
        if (ch === "#")
            break;
        out += ch;
    }
    return out;
}
/** Fallback: resolve a brace-delimited block by `{`/`}` balance, or an indented block. */
function heuristicResolve(request) {
    const lines = request.text.split("\n");
    const startIndex = request.line - 1;
    const opener = lines[startIndex];
    if (opener === undefined || opener.trim() === "" || PURE_CLOSER_RE.test(opener.trim()))
        return null;
    if (stripNonCode(opener).includes("{")) {
        let balance = 0;
        for (let i = startIndex; i < lines.length; i++) {
            for (const ch of stripNonCode(lines[i])) {
                if (ch === "{")
                    balance++;
                else if (ch === "}") {
                    balance--;
                    if (balance === 0)
                        return { start: request.line, end: i + 1 };
                }
            }
        }
        return null;
    }
    const baseIndent = opener.length - opener.trimStart().length;
    let end = startIndex;
    for (let i = startIndex + 1; i < lines.length; i++) {
        const line = lines[i];
        if (line.trim() === "")
            continue;
        const indent = line.length - line.trimStart().length;
        if (indent <= baseIndent)
            break;
        end = i;
    }
    return end > startIndex ? { start: request.line, end: end + 1 } : null;
}
/** Tree-sitter-backed block resolver wired into the hashline {@link Patcher}. */
export const nativeBlockResolver = (request) => {
    const native = loadNativeSearchBinding();
    if (native?.blockRangeAt) {
        const range = native.blockRangeAt({ code: request.text, path: request.path, line: request.line });
        return range ? { start: range.startLine, end: range.endLine } : null;
    }
    return heuristicResolve(request);
};
//# sourceMappingURL=block-resolver.js.map