"""
Create superuser directly via pymysql - no Django setup needed.
Run: python3 /home/xygbfpsg/phingrazuri/create_superuser.py
"""
import pymysql
import pymysql.cursors
import uuid
import hashlib
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
)

# User details
USERNAME   = 'admin'
EMAIL      = 'admin@example.com'
PASSWORD   = 'Grazuri@2026'
FIRST_NAME = 'Admin'
LAST_NAME  = 'User'
PHONE      = '+254700000000'
ROLE       = 'admin'

def make_password(raw_password):
    """Generate Django-compatible pbkdf2_sha256 password hash."""
    import hmac
    import base64
    iterations = 870000
    salt = base64.b64encode(os.urandom(16)).decode('ascii').strip('=')[:22]
    dk = hashlib.pbkdf2_hmac('sha256', raw_password.encode(), salt.encode(), iterations)
    hash_b64 = base64.b64encode(dk).decode('ascii')
    return f"pbkdf2_sha256${iterations}${salt}${hash_b64}"

conn = pymysql.connect(**DB)

print("=" * 60)
print("CREATING SUPERUSER IN users TABLE")
print("=" * 60)

with conn.cursor() as cursor:
    # Check if admin already exists
    cursor.execute("SELECT id, username, is_superuser, is_staff FROM users WHERE username = %s", (USERNAME,))
    existing = cursor.fetchone()

    if existing:
        print(f"\nUser '{USERNAME}' already exists:")
        print(f"  id           = {existing['id']}")
        print(f"  is_superuser = {existing['is_superuser']}")
        print(f"  is_staff     = {existing['is_staff']}")
        print("\nUpdating password and ensuring superuser flags are set...")

        hashed = make_password(PASSWORD)
        cursor.execute("""
            UPDATE users
            SET password = %s, is_superuser = 1, is_staff = 1, is_active = 1,
                role = %s, email = %s, first_name = %s, last_name = %s
            WHERE username = %s
        """, (hashed, ROLE, EMAIL, FIRST_NAME, LAST_NAME, USERNAME))
        conn.commit()
        print(f"✓ Updated. Rows affected: {cursor.rowcount}")
    else:
        print(f"\nCreating new superuser '{USERNAME}'...")
        new_id  = str(uuid.uuid4())
        hashed  = make_password(PASSWORD)

        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, %s, %s, %s,
                %s, %s, %s, %s,
                1, 1, 1,
                NOW(), 'active'
            )
        """, (new_id, USERNAME, EMAIL, hashed,
              FIRST_NAME, LAST_NAME, PHONE, ROLE))
        conn.commit()
        print(f"✓ Created superuser with id={new_id}")

print(f"\nUsername : {USERNAME}")
print(f"Password : {PASSWORD}")
print("Done.")

conn.close()
