"""
clear_bad_sessions.py
---------------------
One-shot fix for the "badly formed hexadecimal UUID string" login error.

Does three things:
  1. Clears all sessions from django_session (removes stale non-UUID session PKs)
  2. Patches users_backends_flag in DB to confirm backend fix is applied
  3. Touches tmp/restart.txt so the Passenger/WSGI process reloads new code

Run on the server:
    python clear_bad_sessions.py
"""

import pymysql
import os
import sys

# ── Database credentials ────────────────────────────────────────────────────
DB_HOST     = "localhost"
DB_PORT     = 3306
DB_NAME     = "xygbfpsg_loans"
DB_USER     = "xygbfpsg_graz"
DB_PASSWORD = "j.ez-xy6##y.rllB"

# ── Path to the Django project root on the server ───────────────────────────
# Adjust if your project lives somewhere else.
PROJECT_ROOT = "/home/xygbfpsg/phingrazuri"
# ────────────────────────────────────────────────────────────────────────────


def step1_clear_sessions():
    print("\n── Step 1: Clear bad sessions ──────────────────────────────────")
    conn = pymysql.connect(
        host=DB_HOST, port=DB_PORT, db=DB_NAME,
        user=DB_USER, password=DB_PASSWORD, charset="utf8mb4",
    )
    try:
        with conn.cursor() as cur:
            cur.execute("SELECT COUNT(*) FROM django_session")
            (before,) = cur.fetchone()
            print(f"  Sessions before: {before}")

            cur.execute("DELETE FROM django_session")
            conn.commit()

            cur.execute("SELECT COUNT(*) FROM django_session")
            (after,) = cur.fetchone()
            print(f"  Sessions after:  {after}")
            print(f"  Deleted {before - after} row(s). ✓")
    finally:
        conn.close()


def step2_patch_backends():
    print("\n── Step 2: Patch users/backends.py ────────────────────────────")
    path = os.path.join(PROJECT_ROOT, "users", "backends.py")

    new_content = '''\
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.db.models import Q

UserModel = get_user_model()

class UUIDModelBackend(ModelBackend):
    """
    Authentication backend for UUID-primary-key users.

    Must be the ONLY entry in AUTHENTICATION_BACKENDS.  Listing the base
    ModelBackend alongside it causes Django to call ModelBackend.get_user()
    which does not guard against invalid UUID strings and raises ValueError
    on stale / pre-migration session data (fatal in Python 3.13).
    """

    def get_user(self, user_id):
        try:
            return UserModel._default_manager.get(pk=user_id)
        except Exception:
            # Catches DoesNotExist, ValueError (badly-formed UUID hex string),
            # and any other error that arises from invalid session data.
            return None

    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        if username is None or password is None:
            return None
        try:
            user = UserModel._default_manager.get(
                Q(username=username) |
                Q(email=username) |
                Q(phone_number=username)
            )
        except UserModel.DoesNotExist:
            # Constant-time dummy hash to prevent timing attacks.
            UserModel().set_password(password)
        except Exception:
            return None
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user
        return None
'''

    if not os.path.exists(path):
        print(f"  WARNING: {path} not found — skipping patch.")
        return

    with open(path, "w", encoding="utf-8") as f:
        f.write(new_content)
    print(f"  Written: {path} ✓")


def step3_patch_settings():
    print("\n── Step 3: Fix AUTHENTICATION_BACKENDS in settings ────────────")
    # The server uses branch_system/settings_production.py → from .settings import *
    # We need to fix branch_system/settings.py (the base).
    settings_path = os.path.join(PROJECT_ROOT, "branch_system", "settings.py")
    if not os.path.exists(settings_path):
        print(f"  WARNING: {settings_path} not found — skipping.")
        return

    with open(settings_path, "r", encoding="utf-8") as f:
        content = f.read()

    # Remove the duplicate ModelBackend entry if it's still there
    old_block = (
        "AUTHENTICATION_BACKENDS = [\n"
        "    'users.backends.UUIDModelBackend',\n"
        "    'django.contrib.auth.backends.ModelBackend',\n"
        "]"
    )
    new_block = (
        "# UUIDModelBackend subclasses ModelBackend — do NOT list ModelBackend\n"
        "# separately; its get_user() doesn't guard against invalid UUID strings.\n"
        "AUTHENTICATION_BACKENDS = [\n"
        "    'users.backends.UUIDModelBackend',\n"
        "]"
    )

    if "django.contrib.auth.backends.ModelBackend" in content:
        content = content.replace(old_block, new_block)
        with open(settings_path, "w", encoding="utf-8") as f:
            f.write(content)
        print(f"  Removed duplicate ModelBackend from {settings_path} ✓")
    else:
        print(f"  settings.py already clean ✓")


def step4_restart_server():
    print("\n── Step 4: Restart Passenger / WSGI process ───────────────────")
    # cPanel / Passenger: touching tmp/restart.txt triggers a reload.
    restart_file = os.path.join(PROJECT_ROOT, "tmp", "restart.txt")
    restart_dir  = os.path.dirname(restart_file)

    os.makedirs(restart_dir, exist_ok=True)

    # Touch the file (create or update mtime)
    with open(restart_file, "a") as f:
        pass
    os.utime(restart_file, None)
    print(f"  Touched {restart_file} ✓")
    print("  The app will reload on the next incoming request.")


if __name__ == "__main__":
    print("=" * 60)
    print("  UUID login fix — one-shot deployment script")
    print("=" * 60)

    try:
        step1_clear_sessions()
    except Exception as e:
        print(f"  ERROR in step 1: {e}")
        sys.exit(1)

    step2_patch_backends()
    step3_patch_settings()
    step4_restart_server()

    print("\n" + "=" * 60)
    print("  Done. Try logging in now.")
    print("=" * 60)
