"""
Fix truncated UUID for admin user by padding it to valid length,
then ensure admin superuser exists and is properly set up.
Run: python3 /home/xygbfpsg/phingrazuri/fix_bad_uuid_users_auto.py
"""
import pymysql
import pymysql.cursors
import re
import uuid
import hashlib
import base64
import os

DB = dict(
    host='localhost',
    port=3306,
    database='xygbfpsg_loans',
    user='xygbfpsg_graz',
    password='j.ez-xy6##y.rllB',
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor
)

UUID_RE  = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')
HEX32_RE = re.compile(r'^[0-9a-f]{32}$')

def add_hyphens(h):
    return '%s-%s-%s-%s-%s' % (h[0:8], h[8:12], h[12:16], h[16:20], h[20:32])

def pad_to_valid_uuid(bad_id):
    """Take a truncated UUID-like string and pad the last segment to make it valid."""
    # Remove hyphens, pad with zeros to 32 chars, re-add hyphens
    stripped = bad_id.replace('-', '')
    if len(stripped) < 32:
        stripped = stripped.ljust(32, '0')
    return add_hyphens(stripped[:32])

def make_password(raw_password):
    iterations = 870000
    salt = base64.b64encode(os.urandom(16)).decode('ascii')[:22]
    dk = hashlib.pbkdf2_hmac('sha256', raw_password.encode(), salt.encode(), iterations)
    hash_b64 = base64.b64encode(dk).decode('ascii')
    return 'pbkdf2_sha256$' + str(iterations) + '$' + salt + '$' + hash_b64

conn = pymysql.connect(**DB)

print("=" * 60)
print("FIX BAD UUIDs + ENSURE ADMIN USER EXISTS")
print("=" * 60)

with conn.cursor() as cursor:
    # Get child tables
    cursor.execute("""
        SELECT TABLE_NAME, COLUMN_NAME
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
        WHERE REFERENCED_TABLE_NAME = 'users'
          AND REFERENCED_COLUMN_NAME = 'id'
          AND TABLE_SCHEMA = 'xygbfpsg_loans'
    """)
    children = cursor.fetchall()

    # Find bad rows
    cursor.execute("""
        SELECT id, username, role, is_superuser, is_staff
        FROM users
        WHERE id NOT REGEXP '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
    """)
    bad_rows = cursor.fetchall()
    print("\nBad rows found: " + str(len(bad_rows)))
    for r in bad_rows:
        print("  id=" + repr(r['id']) + "  username=" + str(r['username']))

    cursor.execute("SET FOREIGN_KEY_CHECKS=0")

    for row in bad_rows:
        old_id = row['id']
        norm = old_id.replace('-', '').lower()

        # Pad to 32 chars if short, then add hyphens
        if len(norm) < 32:
            norm = norm.ljust(32, '0')
        norm = norm[:32]

        if HEX32_RE.match(norm):
            new_id = add_hyphens(norm)
        else:
            new_id = str(uuid.uuid4())

        print("\n  REPAIR: " + repr(old_id) + " -> " + repr(new_id))

        # Update all child tables
        for child in children:
            cursor.execute(
                "UPDATE `" + child['TABLE_NAME'] + "` SET `" + child['COLUMN_NAME'] + "` = %s WHERE `" + child['COLUMN_NAME'] + "` = %s",
                (new_id, old_id)
            )
            if cursor.rowcount:
                print("    updated " + str(cursor.rowcount) + " in " + child['TABLE_NAME'])

        # Update the user row itself
        cursor.execute("UPDATE users SET id = %s WHERE id = %s", (new_id, old_id))
        print("    updated users row: " + str(cursor.rowcount))

    conn.commit()
    cursor.execute("SET FOREIGN_KEY_CHECKS=1")
    conn.commit()

    # Final check
    cursor.execute("""
        SELECT COUNT(*) as cnt FROM users
        WHERE id NOT REGEXP '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
    """)
    remaining = cursor.fetchone()['cnt']
    print("\nBad rows remaining: " + str(remaining))

    # Now ensure admin user is set up correctly
    print("\n" + "=" * 60)
    print("ENSURING ADMIN USER EXISTS AND IS ACTIVE")
    print("=" * 60)

    cursor.execute("SELECT id, username, is_superuser, is_staff, is_active, role FROM users WHERE username = 'admin'")
    admin = cursor.fetchone()

    if admin:
        print("\nAdmin found: id=" + str(admin['id']))
        print("  is_superuser=" + str(admin['is_superuser']) + "  is_staff=" + str(admin['is_staff']) + "  is_active=" + str(admin['is_active']))
        # Reset password and ensure flags
        hashed = make_password('Grazuri@2026')
        cursor.execute("""
            UPDATE users SET password=%s, is_superuser=1, is_staff=1, is_active=1, role='admin', status='active'
            WHERE username='admin'
        """, (hashed,))
        conn.commit()
        print("  Password reset to Grazuri@2026, superuser flags set.")
    else:
        print("\nAdmin not found - creating fresh admin user...")
        new_id = str(uuid.uuid4())
        hashed = make_password('Grazuri@2026')
        cursor.execute("""
            INSERT INTO users (
                id, username, email, password,
                first_name, last_name, phone_number, role,
                is_superuser, is_staff, is_active,
                date_joined, status
            ) VALUES (
                %s, 'admin', 'admin@grazuri.com', %s,
                'Admin', 'User', '+254700000000', 'admin',
                1, 1, 1, NOW(), 'active'
            )
        """, (new_id, hashed))
        conn.commit()
        print("  Created admin with id=" + new_id)

print("\nDone. Login with username=admin password=Grazuri@2026")

conn.close()
