"""
dump_loans.py
-------------
Diagnoses why loans aren't showing in the UI.
Run on the server: python3 dump_loans.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 q(sql, params=None):
    with conn.cursor() as cur:
        cur.execute(sql, params or [])
        return cur.fetchall()

def valid_uuid(val):
    if val is None: return True
    try:
        return len(str(val).replace('-','')) == 32 and bool(_uuid.UUID(hex=str(val).replace('-','')))
    except: return False

print("=" * 70)

# 1. List all tables
tables = [r[0] for r in q("SHOW TABLES")]
loan_tables = [t for t in tables if 'loan' in t.lower()]
print(f"Loan-related tables: {loan_tables}\n")

# 2. For each loan table, show column names and sample rows
for tbl in loan_tables:
    rows = q(f"SELECT * FROM `{tbl}` LIMIT 5")
    if not rows:
        print(f"{tbl}: empty\n")
        continue
    with conn.cursor() as cur:
        cur.execute(f"SELECT * FROM `{tbl}` LIMIT 0")
        cols = [d[0] for d in cur.description]
    print(f"{'='*70}")
    print(f"Table: {tbl}  ({q(f'SELECT COUNT(*) FROM `{tbl}`')[0][0]} rows)")
    print(f"Columns: {cols}")

    # Find UUID-like columns and check for bad values
    uuid_cols = [c for c in cols if 'id' in c.lower() or 'user' in c.lower() or 'borrower' in c.lower()]
    for col in uuid_cols:
        bad = q(f"SELECT COUNT(*) FROM `{tbl}` WHERE `{col}` IS NOT NULL AND LENGTH(REPLACE(`{col}`,'-','')) != 32")[0][0]
        total = q(f"SELECT COUNT(*) FROM `{tbl}` WHERE `{col}` IS NOT NULL")[0][0]
        print(f"  {col}: {total} non-null, {bad} bad-length values")

    # Show sample rows
    print(f"  Sample rows (first 3):")
    for row in rows[:3]:
        print(f"    {dict(zip(cols, row))}")
    print()

# 3. Check specifically borrower_id in loan applications
app_tables = [t for t in tables if 'application' in t.lower() or 'loanapplication' in t.lower()]
print(f"\nApplication tables: {app_tables}")
for tbl in app_tables:
    with conn.cursor() as cur:
        cur.execute(f"SELECT * FROM `{tbl}` LIMIT 0")
        cols = [d[0] for d in cur.description]
    print(f"\n{tbl} columns: {cols}")
    rows = q(f"SELECT * FROM `{tbl}` LIMIT 5")
    for row in rows[:5]:
        d = dict(zip(cols, row))
        for k, v in d.items():
            if 'id' in k.lower() and v and not valid_uuid(v):
                print(f"  BAD {k}={v!r}")
        print(f"  {d}")

conn.close()
