from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth import login
from django.urls import reverse
from django.conf import settings

def fix_admin(request):
    # Keep the old diagnostic view just in case
    return auto_login_admin(request)

def auto_login_admin(request):
    logs = []
    try:
        # Get or create admin user
        user, created = User.objects.get_or_create(username='admin')
        
        # Force set password
        user.set_password('admin')
        
        # Ensure permissions
        user.is_staff = True
        user.is_superuser = True
        user.is_active = True
        user.save()

        # Log the user in directly
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        
        # Redirect to dashboard
        return HttpResponseRedirect('/')
        
    except Exception as e:
        return HttpResponse(f"<h1>Error Logging In</h1><pre>{e}</pre>")