"""
Find and delete users with corrupted/invalid UUID ids.
Run on production: python3 fix_bad_uuid_users.py
"""
import mysql.connector

conn = mysql.connector.connect(
    host='localhost',
    database='xygbfpsg_loans',
    user='xygbfpsg_graz',
    password='j.ez-xy6##y.rllB'
)
cursor = conn.cursor()

print("=" * 60)
print("FINDING BAD UUID ROWS IN users_customuser")
print("=" * 60)

# Find rows where id is NOT a valid UUID format
cursor.execute("""
    SELECT id, username, email, role, first_name, last_name
    FROM users_customuser
    WHERE id NOT REGEXP '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
""")
bad_rows = cursor.fetchall()

print(f"\nFound {len(bad_rows)} rows with invalid UUID ids:\n")
for row in bad_rows:
    print(f"  id={row[0]!r}, username={row[1]!r}, email={row[2]!r}, role={row[3]!r}, name={row[4]} {row[5]}")

if not bad_rows:
    print("No bad rows found! The issue may be elsewhere.")
    cursor.close()
    conn.close()
    exit()

print()
answer = input("Delete these rows? (yes/no): ").strip().lower()

if answer == 'yes':
    cursor.execute("""
        DELETE FROM users_customuser
        WHERE id NOT REGEXP '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
    """)
    conn.commit()
    print(f"\n✓ Deleted {cursor.rowcount} bad rows.")
else:
    print("\nAborted - no rows deleted.")

cursor.close()
conn.close()
print("Done.")
