#!/usr/bin/env python3
"""WBT-023 - date and datetime strings take their fields modulo 2^32: CAST('4294969296-11-21' AS DATE) = 2000-11-21

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 DATE_FORMAT('4294969300-01-01', '%Y-%m-%d')", "SELECT CAST('4294969296-11-21' AS DATE)", "SELECT CAST('2004-01-4294967297' AS DATE)", "SELECT CAST('2004-4294967297-01' AS DATE)", "SELECT GREATEST(DATE '1995-05-05', '10-10-4294967306')", "SELECT CAST('2000-01-01 12:18446744073709551636:00' AS DATETIME)", "SELECT TIMESTAMPDIFF(MONTH, '4294969297-02-01', '2001-05-01')"]
RECORDED = {'mysql': ['((None,),)', '((None,),)', '((None,),)', '((None,),)', "(('16383-15-31',),)", '((None,),)', '((None,),)'], 'mariadb': ["(('2004-01-01',),)", '((datetime.date(2000, 11, 21),),)', '((datetime.date(2004, 1, 1),),)', '((datetime.date(2004, 1, 1),),)', '((datetime.date(2010, 10, 10),),)', '((datetime.datetime(2000, 1, 1, 12, 20),),)', '((3,),)'], 'tidb': ['((None,),)', '((None,),)', '((None,),)', '((None,),)', "(('1995-05-05',),)", '((None,),)', '((None,),)']}


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())
