#!/usr/bin/env python3
"""WBT-028 - ST_GeomFromText/GeomFromText/ST_GeomFromGeoJSON take the SRID modulo 2^32

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 ST_SRID(ST_GeomFromText('POINT(0 0)', 4294967296)), ST_SRID(ST_GeomFromText('POINT(0 0)', 4294967297)), ST_SRID(ST_GeomFromText('POINT(0 0)', 4294967295))", "SELECT SRID(GeomFromText('LineString(1 1,2 2)', 4294967397))", 'SELECT ST_SRID(ST_GeomFromGeoJSON(\'{"type": "Point", "coordinates": [102.0, 0.0]}\', NULL, 4294971622))']
RECORDED = {'mysql': ['ERROR 1690', 'ERROR 1064', '((None,),)'], 'mariadb': ['((0, 1, 4294967295),)', '((101,),)', '((4326,),)'], 'tidb': ['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())
