#!/usr/bin/env python3
"""WBT-031 - dynamic-column functions truncate a column number to 32 bits before the 0..65535 check

Runs the witness on the latest MySQL, MariaDB and TiDB (ports 3320, 3410, 4110 on node1)
and compares each affected engine's answers with the buggy answers recorded on
2026-10-08 (VERIFY log). Exits 1 while an affected engine still gives the recorded
buggy answers, 0 when they changed (re-check by hand then).

  python3 repro.py [mysql_port mariadb_port tidb_port]
"""
import sys
import pymysql

PORTS = dict(zip(('mysql', 'mariadb', 'tidb'), [int(p) for p in sys.argv[1:4]] or [3320, 3410, 4110]))
WRONG = ['mariadb']
STATEMENTS = ["SELECT COLUMN_JSON(COLUMN_CREATE(65535, 'a'))", "SELECT COLUMN_JSON(COLUMN_CREATE(65536, 'a'))", "SELECT COLUMN_JSON(COLUMN_CREATE(4294967297, 'a'))", "SELECT COLUMN_JSON(COLUMN_CREATE(4294967296, 'a'))", "SELECT COLUMN_JSON(COLUMN_DELETE(COLUMN_CREATE(1, 'a', 2, 'b'), 4294967297))", "SELECT COLUMN_JSON(COLUMN_ADD(COLUMN_CREATE(1, 'a'), 4294967298, 'b'))"]
RECORDED = {'mysql': ['ERROR 1305', 'ERROR 1305', 'ERROR 1305', 'ERROR 1305', 'ERROR 1305', 'ERROR 1305'], 'mariadb': ['((\'{"65535":"a"}\',),)', 'ERROR 1921', '((\'{"1":"a"}\',),)', '((\'{"0":"a"}\',),)', '((\'{"2":"b"}\',),)', '((\'{"1":"a","2":"b"}\',),)'], 'tidb': ['ERROR 1305', 'ERROR 1305', 'ERROR 1305', 'ERROR 1305', 'ERROR 1305', 'ERROR 1305']}


def run(port):
    out = []
    c = pymysql.connect(host='127.0.0.1', port=port, user='root', password='', autocommit=True)
    cur = c.cursor()
    cur.execute('CREATE DATABASE IF NOT EXISTS wbt_repro')
    cur.execute('USE wbt_repro')
    for st in STATEMENTS:
        try:
            cur.execute(st)
            out.append(repr(cur.fetchall() if cur.description else 'ok'))
        except Exception as e:
            out.append('ERROR ' + str(e.args[0] if e.args else e))
    return out


def main():
    present = 0
    for eng, port in PORTS.items():
        got = run(port)
        same = got == RECORDED.get(eng)
        tag = ('BUG (unchanged)' if same else 'CHANGED') if eng in WRONG else 'reference'
        present += eng in WRONG and same
        print('== %s (%d): %s' % (eng, port, tag))
        for st, r in zip(STATEMENTS, got):
            print('  > %s\n    %s' % (st, r))
    return 1 if present else 0


if __name__ == '__main__':
    sys.exit(main())
