"""
dump_auditlog.py
----------------
Dumps the utils_auditlog table to identify bad user_id values.
Run on the server: python3 dump_auditlog.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",
)

def is_valid_uuid(val):
    if val is None:
        return True   # NULL FK is fine
    try:
        hex_val = str(val).replace('-', '')
        return len(hex_val) == 32 and bool(_uuid.UUID(hex=hex_val))
    except (ValueError, AttributeError):
        return False

with conn.cursor() as cur:
    # Check which tables actually exist
    cur.execute("""
        SELECT TABLE_NAME FROM information_schema.TABLES
        WHERE TABLE_SCHEMA=DATABASE()
        AND TABLE_NAME IN ('utils_auditlog','accounting_auditlog')
    """)
    tables = [r[0] for r in cur.fetchall()]
    print(f"Audit log tables found: {tables}\n")

    for table in tables:
        print(f"{'='*60}")
        print(f"Table: {table}")
        print(f"{'='*60}")

        # Get column names
        cur.execute(f"SELECT * FROM `{table}` LIMIT 0")
        cols = [d[0] for d in cur.description]
        print(f"Columns: {cols}\n")

        # Get rows
        cur.execute(f"SELECT * FROM `{table}` ORDER BY id DESC LIMIT 20")
        rows = cur.fetchall()
        print(f"Total rows (showing last 20 of all):")

        bad_rows = []
        for row in rows:
            row_dict = dict(zip(cols, row))
            user_id = row_dict.get('user_id')
            obj_id  = row_dict.get('object_id', '')

            valid_user = is_valid_uuid(user_id)
            flag = "" if valid_user else " ← BAD user_id"

            print(f"  id={row_dict.get('id')}  user_id={user_id!r}{flag}  action={row_dict.get('action')}  model={row_dict.get('model_name')}")
            if not valid_user:
                bad_rows.append(row_dict)

        if bad_rows:
            print(f"\n  BAD ROWS in {table}: {len(bad_rows)}")
        else:
            print(f"\n  All user_id values are valid in {table}.")
        print()

conn.close()
