import pathlib
import re

s = pathlib.Path(__file__).with_name("_check.js").read_text(encoding="utf-8")
lines = s.splitlines()

def strip_strings(line):
    t = re.sub(r"//.*", "", line)
    t = re.sub(r'"([^"\\]|\\.)*"', "", t)
    t = re.sub(r"'([^'\\]|\\.)*'", "", t)
    # template literals: crude — remove ${...} and backtick strings in chunks
    out = []
    i = 0
    while i < len(t):
        if t[i] == "`":
            i += 1
            while i < len(t):
                if t[i] == "\\":
                    i += 2
                    continue
                if t[i] == "`":
                    i += 1
                    break
                if t[i] == "$" and i + 1 < len(t) and t[i + 1] == "{":
                    i += 2
                    depth = 1
                    while i < len(t) and depth:
                        if t[i] == "{":
                            depth += 1
                        elif t[i] == "}":
                            depth -= 1
                        i += 1
                    continue
                i += 1
            continue
        out.append(t[i])
        i += 1
    return "".join(out)

bal = 0
zeros = []
for i, line in enumerate(lines, 1):
    t = strip_strings(line)
    for ch in t:
        if ch == "{":
            bal += 1
        elif ch == "}":
            bal -= 1
    if bal == 0 and i > 2:
        zeros.append(i)

print("zero balance lines (after start):", zeros[-20:])
print("final", bal)
