"""
Scan ALL tables for bad UUID values in any id/uuid column.
Run: python3 /home/xygbfpsg/phingrazuri/find_all_bad_uuids.py
"""
import pymysql
import pymysql.cursors

DB = dict(
    host='localhost',
    port=3306,
    database='xygbfpsg_loans',
    user='xygbfpsg_graz',
    password='j.ez-xy6##y.rllB',
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor
)

conn = pymysql.connect(**DB)

print("=" * 60)
print("SCANNING ALL TABLES FOR BAD UUID VALUES")
print("=" * 60)

VALID_UUID = r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'

with conn.cursor() as cursor:
    # Get all tables
    cursor.execute("SHOW TABLES")
    tables = [list(r.values())[0] for r in cursor.fetchall()]

    for table in tables:
        # Get columns
        cursor.execute("DESCRIBE `" + table + "`")
        cols = cursor.fetchall()

        for col in cols:
            col_name = col['Field']
            col_type = col['Type'].lower()

            # Only check varchar/char columns that look like UUID fields
            if ('varchar' in col_type or 'char' in col_type) and \
               ('id' in col_name.lower() or 'uuid' in col_name.lower()):

                try:
                    cursor.execute(
                        "SELECT COUNT(*) as cnt FROM `" + table + "` WHERE `" + col_name + "` IS NOT NULL "
                        "AND `" + col_name + "` != '' "
                        "AND `" + col_name + "` NOT REGEXP '" + VALID_UUID + "'"
                    )
                    result = cursor.fetchone()
                    if result and result['cnt'] > 0:
                        # Get sample bad values
                        cursor.execute(
                            "SELECT `" + col_name + "` as bad_val FROM `" + table + "` "
                            "WHERE `" + col_name + "` IS NOT NULL "
                            "AND `" + col_name + "` != '' "
                            "AND `" + col_name + "` NOT REGEXP '" + VALID_UUID + "' "
                            "LIMIT 3"
                        )
                        samples = [r['bad_val'] for r in cursor.fetchall()]
                        print("\nBAD: " + table + "." + col_name + " (" + str(result['cnt']) + " rows)")
                        for s in samples:
                            print("  " + repr(s))
                except Exception as e:
                    pass  # skip columns that can't be queried this way

print("\nScan complete.")
conn.close()
