from pathlib import Path
import re
text = Path('SQL/database.sql').read_text(encoding='utf-8', errors='replace')
insert_re = re.compile(r'INSERT INTO `([^`]+)` \(([^)]+)\) VALUES\s*(.*?);\s*(?=-- |\Z)', re.S)
for m in insert_re.finditer(text):
    table = m.group(1)
    cols = [c.strip(' `') for c in m.group(2).split(',')]
    data = m.group(3).strip()
    # split top-level tuples
    tuples = []
    depth = 0
    quote = None
    esc = False
    buf = ''
    for ch in data:
        if quote:
            buf += ch
            if esc:
                esc = False
            elif ch == '\\':
                esc = True
            elif ch == quote:
                quote = None
        elif ch in "'\"":
            quote = ch
            buf += ch
        elif ch == '(':
            depth += 1
            buf += ch
        elif ch == ')':
            depth -= 1
            buf += ch
            if depth == 0:
                tuples.append(buf)
                buf = ''
        else:
            if depth > 0 or not ch.isspace():
                buf += ch
    for idx, tup in enumerate(tuples, start=1):
        content = tup[1:-1]
        values = []
        depth = 0
        quote = None
        esc = False
        buf = ''
        for ch in content:
            if quote:
                buf += ch
                if esc:
                    esc = False
                elif ch == '\\':
                    esc = True
                elif ch == quote:
                    quote = None
            elif ch in "'\"":
                quote = ch
                buf += ch
            elif ch == '(':
                depth += 1
                buf += ch
            elif ch == ')':
                depth -= 1
                buf += ch
            elif ch == ',' and depth == 0:
                values.append(buf.strip())
                buf = ''
            else:
                buf += ch
        if buf.strip():
            values.append(buf.strip())
        if len(values) != len(cols):
            print('MISMATCH', table, 'cols', len(cols), 'row', idx, 'vals', len(values), 'expected', len(cols))
            print(tup)
            print('---')
            break
