"""
fix_admin_login.py
------------------
Fixes the admin login on the production server.

The users.id column is VARCHAR(32) — UUIDs are stored as 32 hex chars with
NO dashes (e.g. "c4c23850a3a448f8a29fd8de3a2bxxxx").  The admin row currently
has a corrupt/truncated value that isn't a valid UUID, so every PK lookup
explodes.  The password hash was also set by a manual reimplementation that
doesn't match Django's exact format.

This script:
  1. Replaces the bad id with a valid 32-char hex UUID (no dashes, fits VARCHAR(32))
  2. Cascades that change to every FK column in every table that references it
  3. Resets the password using Django's real make_password()
  4. Forces is_active / is_superuser / status flags
  5. Clears all sessions (stale sessions still cause UUID errors on first hit)
  6. Touches tmp/restart.txt to reload Passenger

Run on the server:
    python3 fix_admin_login.py
"""

import sys, os

PROJECT_ROOT = '/home/xygbfpsg/phingrazuri'
sys.path.insert(0, PROJECT_ROOT)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
os.environ.setdefault('DB_NAME',     'xygbfpsg_loans')
os.environ.setdefault('DB_USER',     'xygbfpsg_graz')
os.environ.setdefault('DB_PASSWORD', 'j.ez-xy6##y.rllB')
os.environ.setdefault('DB_HOST',     'localhost')
os.environ.setdefault('DB_PORT',     '3306')

import django
django.setup()

from django.contrib.auth.hashers import make_password, check_password
from django.db import connection
import uuid as _uuid

USERNAME = 'admin'
PASSWORD = 'Grazuri@2026'

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

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

def fetchone(query, params=None):
    with connection.cursor() as cur:
        cur.execute(query, params or [])
        return cur.fetchone()

def fetchall(query, params=None):
    with connection.cursor() as cur:
        cur.execute(query, params or [])
        return cur.fetchall()

def table_exists(name):
    row = fetchone(
        "SELECT 1 FROM information_schema.TABLES "
        "WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=%s", [name]
    )
    return bool(row)

def column_exists(table, col):
    row = fetchone(
        "SELECT 1 FROM information_schema.COLUMNS "
        "WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=%s AND COLUMN_NAME=%s",
        [table, col]
    )
    return bool(row)

# ── Step 1: find the user ─────────────────────────────────────────────────────
print(f"\n[1] Looking up '{USERNAME}' …")
row = fetchone(
    "SELECT id, password, is_active, is_superuser, status FROM users WHERE username=%s",
    [USERNAME]
)
if not row:
    print("    Not found — creating fresh superuser …")
    new_id_hex = _uuid.uuid4().hex          # 32 hex chars, no dashes
    new_hash   = make_password(PASSWORD)
    sql("""
        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_hex, USERNAME, 'admin@example.com', new_hash,
          'Admin', 'User', '+254700000000', 'admin'])
    print(f"    Created with id={new_id_hex} ✓")
    print(f"\n{'='*60}\n  username: {USERNAME}  password: {PASSWORD}\n{'='*60}")
    sys.exit(0)

raw_id, old_hash, is_active, is_superuser, status = row
print(f"    id={raw_id!r}  is_active={is_active}  is_superuser={is_superuser}  status={status}")

# ── Step 2: validate the UUID ────────────────────────────────────────────────
print("\n[2] Validating id …")

# Normalise: strip dashes so we can test the raw hex
hex_id = str(raw_id).replace('-', '')
id_ok  = len(hex_id) == 32
if id_ok:
    try:
        _uuid.UUID(hex=hex_id)
    except (ValueError, AttributeError):
        id_ok = False

if id_ok:
    print(f"    id is a valid 32-char hex UUID ✓  (no change needed)")
    new_id_hex = hex_id
else:
    new_id_hex = _uuid.uuid4().hex          # fresh 32-char hex UUID
    print(f"    BAD id: {raw_id!r}  ({len(hex_id)} hex chars)")
    print(f"    New id: {new_id_hex}")

    # Discover every FK column pointing at users.id from information_schema
    # so we don't have to hardcode table names
    fk_rows = fetchall("""
        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'
    """)

    print(f"    Found {len(fk_rows)} FK column(s) referencing users.id")

    with connection.cursor() as cur:
        # Temporarily disable FK checks so we can update freely
        cur.execute("SET FOREIGN_KEY_CHECKS=0")
        for tbl, col in fk_rows:
            try:
                cur.execute(
                    f"UPDATE `{tbl}` SET `{col}`=%s WHERE `{col}`=%s",
                    [new_id_hex, raw_id]
                )
                if cur.rowcount:
                    print(f"    Cascaded {cur.rowcount} row(s) → {tbl}.{col}")
            except Exception as e:
                print(f"    (skipped {tbl}.{col}: {e})")
        # Update the PK itself
        cur.execute("UPDATE users SET id=%s WHERE username=%s", [new_id_hex, USERNAME])
        cur.execute("SET FOREIGN_KEY_CHECKS=1")
        connection.connection.commit()
    print(f"    PK updated to {new_id_hex} ✓")

# ── Step 3: fix password ──────────────────────────────────────────────────────
print("\n[3] Verifying password hash …")
hash_ok = False
try:
    hash_ok = check_password(PASSWORD, old_hash)
except Exception as e:
    print(f"    check_password() raised: {e}")

if hash_ok:
    print(f"    Hash is good ✓")
else:
    print(f"    Hash bad — regenerating …")
    new_hash = make_password(PASSWORD)
    sql("UPDATE users SET password=%s WHERE username=%s", [new_hash, USERNAME])
    assert check_password(PASSWORD, new_hash), "ERROR: hash still fails after reset"
    print(f"    New hash set and verified ✓")

# ── Step 4: account flags ─────────────────────────────────────────────────────
print("\n[4] Ensuring account flags …")
sql("""
    UPDATE users
    SET is_active=1, is_superuser=1, is_staff=1, status='active'
    WHERE username=%s
""", [USERNAME])
print("    is_active=1  is_superuser=1  is_staff=1  status='active' ✓")

# ── Step 5: clear all sessions ───────────────────────────────────────────────
print("\n[5] Clearing stale sessions …")
n = sql("DELETE FROM django_session")
print(f"    Deleted {n} session row(s) ✓")

# ── Step 6: restart Passenger ────────────────────────────────────────────────
print("\n[6] Restarting Passenger …")
restart_path = os.path.join(PROJECT_ROOT, 'tmp', 'restart.txt')
os.makedirs(os.path.dirname(restart_path), exist_ok=True)
with open(restart_path, 'a'):
    pass
os.utime(restart_path, None)
print(f"    Touched {restart_path} ✓")

# ── Done ──────────────────────────────────────────────────────────────────────
print(f"\n{'='*60}")
print(f"  Login ready:")
print(f"    Username : {USERNAME}")
print(f"    Password : {PASSWORD}")
print(f"{'='*60}")
