"""
fix_auditlog_fks.py
-------------------
Finds every row in utils_auditlog (and any other table) whose user_id column
contains the old truncated/bad UUID from the original admin account, and
updates it to the current admin's valid UUID.

Also scans ALL tables for any column that references users.id and contains
the bad value, so nothing is missed.

Run on the server: python3 fix_auditlog_fks.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"

# The bad truncated UUID still sitting in FK columns
BAD_UUID = '82bf102f-725e-4962-a211-4e3591ce'

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

def q(sql, params=None):
    with conn.cursor() as cur:
        cur.execute(sql, params or [])
        return cur.fetchall()

def run(sql, params=None):
    with conn.cursor() as cur:
        cur.execute(sql, params or [])
        return cur.rowcount

print("=" * 60)
print("  fix_auditlog_fks.py")
print("=" * 60)

# ── Step 1: get the current admin's valid id ──────────────────────────────────
print("\n[1] Finding current admin id …")
rows = q("SELECT id, username FROM users WHERE username='admin'")
if not rows:
    print("    ERROR: no admin user found.")
    conn.close()
    exit(1)
good_id, username = rows[0]
print(f"    Current admin: username={username!r}  id={good_id!r}  (len={len(str(good_id))})")

# ── Step 2: discover all FK columns pointing at users.id ─────────────────────
print("\n[2] Discovering FK columns referencing users.id …")
fk_cols = q("""
    SELECT kcu.TABLE_NAME, kcu.COLUMN_NAME
    FROM information_schema.KEY_COLUMN_USAGE kcu
    JOIN information_schema.TABLE_CONSTRAINTS tc
      ON tc.CONSTRAINT_NAME  = kcu.CONSTRAINT_NAME
     AND tc.TABLE_SCHEMA     = kcu.TABLE_SCHEMA
     AND tc.TABLE_NAME       = kcu.TABLE_NAME
    WHERE kcu.TABLE_SCHEMA            = DATABASE()
      AND kcu.REFERENCED_TABLE_NAME   = 'users'
      AND kcu.REFERENCED_COLUMN_NAME  = 'id'
      AND tc.CONSTRAINT_TYPE          = 'FOREIGN KEY'
    ORDER BY kcu.TABLE_NAME, kcu.COLUMN_NAME
""")
print(f"    Found {len(fk_cols)} FK column(s):")
for tbl, col in fk_cols:
    print(f"      {tbl}.{col}")

# ── Step 3: also explicitly include utils_auditlog.user_id in case it has
#    no FK constraint defined (some audit tables skip the constraint)
extra = [('utils_auditlog', 'user_id')]
all_targets = list(fk_cols)
for item in extra:
    if item not in all_targets:
        all_targets.append(item)

# ── Step 4: fix every table ───────────────────────────────────────────────────
print(f"\n[3] Replacing bad user_id {BAD_UUID!r} → {good_id!r} …")
total_fixed = 0

try:
    with conn.cursor() as cur:
        cur.execute("SET FOREIGN_KEY_CHECKS=0")

        for tbl, col in all_targets:
            # Check if table exists
            exists = q(
                "SELECT 1 FROM information_schema.TABLES "
                "WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=%s", [tbl]
            )
            if not exists:
                continue

            # Count affected rows first
            count_rows = q(
                f"SELECT COUNT(*) FROM `{tbl}` WHERE `{col}`=%s", [BAD_UUID]
            )
            count = count_rows[0][0] if count_rows else 0
            if count == 0:
                continue

            cur.execute(
                f"UPDATE `{tbl}` SET `{col}`=%s WHERE `{col}`=%s",
                [good_id, BAD_UUID]
            )
            affected = cur.rowcount
            total_fixed += affected
            print(f"    {tbl}.{col}: fixed {affected} row(s)")

        cur.execute("SET FOREIGN_KEY_CHECKS=1")

    conn.commit()
    print(f"\n    Total rows fixed: {total_fixed} ✓")

except Exception as e:
    conn.rollback()
    print(f"\n    ERROR — rolled back: {e}")
    conn.close()
    exit(1)

# ── Step 5: verify no bad values remain ──────────────────────────────────────
print("\n[4] Verifying …")
remaining = q(
    "SELECT COUNT(*) FROM utils_auditlog WHERE user_id=%s", [BAD_UUID]
)
count_left = remaining[0][0] if remaining else 0
if count_left == 0:
    print(f"    utils_auditlog: 0 bad rows remaining ✓")
else:
    print(f"    WARNING: {count_left} bad rows still in utils_auditlog")

conn.close()
print(f"\n{'='*60}")
print("  Done. Reload the dashboard — it should work now.")
print(f"{'='*60}")
