import re, sys

src = open("/tmp/opencode/stage2.lua", encoding="utf-8").read()

out = []
i = 0
n = len(src)

def long_bracket_end(s, start):
    # s[start] == '['
    j = start + 1
    eq = 0
    while j < n and s[j] == '=':
        eq += 1
        j += 1
    if j < n and s[j] == '[':
        close = ']' + '=' * eq + ']'
        k = s.find(close, j + 1)
        return (k + len(close)) if k != -1 else n
    return None

while i < n:
    c = src[i]
    if c == '-' and src.startswith('--', i):
        j = i + 2
        end = None
        if j < n and src[j] == '[':
            end = long_bracket_end(src, j)
        if end is not None:
            i = end
        else:
            k = src.find('\n', i)
            i = n if k == -1 else k
        continue
    if c == '[':
        end = long_bracket_end(src, i)
        if end is not None:
            out.append(src[i:end])
            i = end
            continue
    if c in ('"', "'"):
        q = c
        j = i + 1
        while j < n:
            if src[j] == '\\':
                j += 2
                continue
            if src[j] == q:
                j += 1
                break
            j += 1
        out.append(src[i:j])
        i = j
        continue
    out.append(c)
    i += 1

res = ''.join(out)
# drop trailing whitespace on each line and collapse blank runs
lines = [ln.rstrip() for ln in res.split('\n')]
clean = []
blank = 0
for ln in lines:
    if ln == '':
        blank += 1
        if blank > 2:
            continue
    else:
        blank = 0
    clean.append(ln)
res = '\n'.join(clean)

# sanity: no print/warn calls remain
for pat in (r'\bprint\s*\(', r'\bwarn\s*\('):
    m = re.findall(pat, res)
    if m:
        print("remaining", pat, len(m))

open("/opt/ws-remote/scripts/soleezz/w-script/W.lua", "w", encoding="utf-8").write(res)
print("wrote", len(res), "bytes;", res.count('\n') + 1, "lines")
