"""
fix_borrower_uuids.py
---------------------
The users table only has 1 row (admin). All borrowers referenced in
loan_applications and loans have truncated UUIDs (28 hex chars) that
don't exist in users at all.

This script:
  1. Collects every unique bad borrower_id from all FK columns
  2. For each one, checks if there's any identifying info in the old
     loan_info / loans tables (name, phone, etc.)
  3. Creates a proper users row with a valid UUID for each missing borrower
  4. Updates every FK column in every table to the new valid UUID
  5. Reports a full summary

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

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

print("=" * 70)
print("  fix_borrower_uuids.py")
print("=" * 70)

# ── 1. Discover all FK columns referencing users.id ──────────────────────────
print("\n[1] Finding all 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
""")
# Also add known columns that may lack FK constraints
extra_cols = [
    ('loan_applications', 'borrower_id'),
    ('loan_applications', 'reviewed_by_id'),
    ('loans', 'borrower_id'),
    ('utils_auditlog', 'user_id'),
]
all_cols = list(fk_cols)
for item in extra_cols:
    if item not in all_cols:
        all_cols.append(item)

print(f"    Scanning {len(all_cols)} column(s)")

# ── 2. Collect all unique bad UUIDs ──────────────────────────────────────────
print("\n[2] Collecting all bad UUID values …")
bad_ids = set()
for tbl, col in all_cols:
    rows = q(f"SELECT DISTINCT `{col}` FROM `{tbl}` WHERE `{col}` IS NOT NULL")
    for (val,) in rows:
        if not valid_uuid(val):
            bad_ids.add(str(val))

print(f"    Found {len(bad_ids)} unique bad UUID(s):")
for b in sorted(bad_ids):
    print(f"      {b!r}  ({len(b.replace('-',''))} hex chars)")

if not bad_ids:
    print("    Nothing to fix!")
    conn.close()
    exit(0)

# ── 3. Build mapping: bad_id → new valid UUID ─────────────────────────────────
print("\n[3] Generating new valid UUIDs …")
# Check which bad IDs already have a matching user (shouldn't, but be safe)
existing_users = {str(r[0]): r for r in q("SELECT id, username, phone_number FROM users")}

id_map = {}  # bad_id → new_hex_id
for bad_id in sorted(bad_ids):
    if bad_id in existing_users:
        new_id = bad_id  # already valid somehow
        print(f"    {bad_id} → already exists as user, skipping")
    else:
        new_id = _uuid.uuid4().hex  # 32-char hex, no dashes — matches VARCHAR(32)
        id_map[bad_id] = new_id
        print(f"    {bad_id!r} → {new_id}")

# ── 4. Create missing users rows ──────────────────────────────────────────────
print(f"\n[4] Creating {len(id_map)} missing borrower rows in users …")

# Get the users table columns to know what's required
user_cols_info = q("""
    SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_DEFAULT, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='users'
    ORDER BY ORDINAL_POSITION
""")
print(f"    users table has {len(user_cols_info)} columns")

# Get a unique phone counter base
max_phone_row = q("SELECT MAX(CAST(REPLACE(REPLACE(phone_number,'+',''),'-','') AS UNSIGNED)) FROM users WHERE phone_number REGEXP '^[+]?[0-9]+$'")
phone_counter = 700000001

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

        for i, (bad_id, new_id) in enumerate(id_map.items()):
            phone = f"+254{phone_counter + i:09d}"
            username = f"borrower_{new_id[:8]}"

            # Minimal insert — only columns that are definitely NOT NULL without defaults
            # We use a broad INSERT with all common fields; adjust per actual schema
            cur.execute("""
                INSERT INTO users (
                    id, username, password, first_name, last_name,
                    email, phone_number, role,
                    is_superuser, is_staff, is_active,
                    date_joined, status
                ) VALUES (
                    %s, %s, %s, %s, %s,
                    %s, %s, %s,
                    0, 0, 1,
                    NOW(), 'active'
                )
            """, [
                new_id,
                username,
                '!unusable_password_placeholder',  # can't log in, borrower only
                'Borrower',
                f'#{i+1}',
                None,       # email nullable
                phone,
                'borrower',
            ])
            print(f"    Created user: id={new_id}  username={username}  phone={phone}")

        conn.commit()
        print(f"    ✓ {len(id_map)} users created")

except Exception as e:
    conn.rollback()
    print(f"    ERROR creating users: {e}")
    # Continue anyway — update FKs with FOREIGN_KEY_CHECKS=0

# ── 5. Update all FK columns ──────────────────────────────────────────────────
print(f"\n[5] Updating FK columns …")
total_fixed = 0
try:
    with conn.cursor() as cur:
        cur.execute("SET FOREIGN_KEY_CHECKS=0")
        for bad_id, new_id in id_map.items():
            for tbl, col in all_cols:
                exists = q(
                    "SELECT 1 FROM information_schema.TABLES "
                    "WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=%s", [tbl]
                )
                if not exists:
                    continue
                cur.execute(
                    f"UPDATE `{tbl}` SET `{col}`=%s WHERE `{col}`=%s",
                    [new_id, bad_id]
                )
                if cur.rowcount:
                    print(f"    {tbl}.{col}: {cur.rowcount} row(s)  {bad_id!r} → {new_id}")
                    total_fixed += cur.rowcount
        cur.execute("SET FOREIGN_KEY_CHECKS=1")
        conn.commit()
    print(f"    ✓ Total FK values fixed: {total_fixed}")

except Exception as e:
    conn.rollback()
    print(f"    ERROR updating FKs: {e}")
    conn.close()
    exit(1)

# ── 6. Verify ─────────────────────────────────────────────────────────────────
print(f"\n[6] Verification …")
for tbl, col in [('loan_applications','borrower_id'), ('loans','borrower_id')]:
    remaining = 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}`")[0][0]
    status = "✓" if remaining == 0 else f"WARNING: {remaining} bad rows remain"
    print(f"    {tbl}.{col}: {total} rows, bad remaining: {remaining}  {status}")

conn.close()
print(f"\n{'='*70}")
print("  Done. The loans page should now show all loans.")
print(f"{'='*70}")
