"""
dump_users.py
-------------
Dumps all rows from the users table with their raw id values and validity status.
Run on the server: python3 dump_users.py
"""
import pymysql
import uuid as _uuid

DB_HOST     = "localhost"
DB_PORT     = 3306
DB_NAME     = "xygbfpsg_loans"
DB_USER     = "xygbfpsg_graz"
DB_PASSWORD = "j.ez-xy6##y.rllB"

conn = pymysql.connect(
    host=DB_HOST, port=DB_PORT, db=DB_NAME,
    user=DB_USER, password=DB_PASSWORD, charset="utf8mb4",
)

with conn.cursor() as cur:
    cur.execute("""
        SELECT id, username, email, phone_number, role,
               is_active, is_superuser, status,
               LENGTH(id) as id_len
        FROM users
        ORDER BY role, username
    """)
    rows = cur.fetchall()

conn.close()

def is_valid_uuid(val):
    if val is None:
        return False
    try:
        _uuid.UUID(str(val).replace('-', ''), version=4)
        return len(str(val).replace('-', '')) == 32
    except (ValueError, AttributeError):
        return False

print(f"{'ID':<36}  {'LEN':>3}  {'VALID':>5}  {'ROLE':<12}  {'USERNAME':<20}  {'STATUS'}")
print("-" * 100)
bad = []
for row in rows:
    raw_id, username, email, phone, role, is_active, is_superuser, status, id_len = row
    valid = is_valid_uuid(raw_id)
    flag = "  OK" if valid else " BAD"
    print(f"{str(raw_id):<36}  {id_len:>3}  {flag}  {str(role):<12}  {str(username):<20}  {status}")
    if not valid:
        bad.append(row)

print()
print(f"Total: {len(rows)}  |  Bad UUIDs: {len(bad)}")
if bad:
    print("\nBAD UUID ROWS:")
    for row in bad:
        print(f"  id={row[0]!r}  username={row[1]!r}  role={row[4]!r}")
