#!/usr/bin/env python
"""
Script to check and fix authentication issues in cPanel environment
"""
import os
import sys
import django
from datetime import datetime

# Setup Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from django.conf import settings

User = get_user_model()

def print_separator():
    print("\n" + "=" * 60 + "\n")

def check_settings():
    """Check Django settings"""
    print("Checking Django Settings...")
    
    # Check Authentication Backends
    print("\nAuthentication Backends:")
    try:
        backends = settings.AUTHENTICATION_BACKENDS
        for backend in backends:
            print(f"✓ {backend}")
    except Exception as e:
        print(f"✗ Error getting authentication backends: {str(e)}")
    
    # Check User Model
    print("\nUser Model:")
    print(f"✓ AUTH_USER_MODEL = {settings.AUTH_USER_MODEL}")
    
    # Check Session Settings
    print("\nSession Settings:")
    print(f"✓ SESSION_COOKIE_AGE = {getattr(settings, 'SESSION_COOKIE_AGE', 'Not set')}")
    print(f"✓ SESSION_EXPIRE_AT_BROWSER_CLOSE = {getattr(settings, 'SESSION_EXPIRE_AT_BROWSER_CLOSE', 'Not set')}")
    print(f"✓ SESSION_COOKIE_SECURE = {getattr(settings, 'SESSION_COOKIE_SECURE', 'Not set')}")

def check_users():
    """Check user accounts"""
    print("Checking User Accounts...")
    
    test_users = [
        {
            'email': 'admin@branchbusinessadvance.com',
            'password': 'admin123',
            'role': 'admin',
            'is_staff': True,
            'is_superuser': True
        },
        {
            'email': 'officer@branchbusinessadvance.com',
            'password': 'officer123',
            'role': 'loan_officer',
            'is_staff': True,
            'is_superuser': False
        },
        {
            'email': 'client@branchbusinessadvance.com',
            'password': 'client123',
            'role': 'borrower',
            'is_staff': False,
            'is_superuser': False
        }
    ]
    
    for user_data in test_users:
        print(f"\nChecking {user_data['email']}...")
        try:
            user = User.objects.get(email=user_data['email'])
            print(f"✓ User exists")
            print(f"✓ Username: {user.username}")
            print(f"✓ Role: {user.role}")
            print(f"✓ Status: {user.status}")
            print(f"✓ Is Active: {user.is_active}")
            
            # Update password
            user.set_password(user_data['password'])
            user.save()
            print(f"✓ Password updated")
            
            # Update role and permissions if needed
            if user.role != user_data['role']:
                user.role = user_data['role']
                user.save()
                print(f"✓ Role updated to {user_data['role']}")
            
            if user.is_staff != user_data['is_staff']:
                user.is_staff = user_data['is_staff']
                user.save()
                print(f"✓ Staff status updated")
            
            if user.is_superuser != user_data['is_superuser']:
                user.is_superuser = user_data['is_superuser']
                user.save()
                print(f"✓ Superuser status updated")
            
        except User.DoesNotExist:
            # Create user if doesn't exist
            user = User.objects.create_user(
                username=user_data['email'],
                email=user_data['email'],
                password=user_data['password'],
                role=user_data['role'],
                is_staff=user_data['is_staff'],
                is_superuser=user_data['is_superuser'],
                is_active=True,
                status='active'
            )
            print(f"✓ User created with all permissions")

def check_backend_file():
    """Check if backend file exists and is correct"""
    print("Checking Backend File...")
    
    backend_path = os.path.join('users', 'backends.py')
    if os.path.exists(backend_path):
        print(f"✓ Backend file exists at {backend_path}")
        
        # Read and verify content
        try:
            with open(backend_path, 'r') as f:
                content = f.read()
                if 'EmailOrPhoneBackend' in content:
                    print("✓ Backend file contains correct class")
                else:
                    print("✗ Backend file might be incorrect")
        except Exception as e:
            print(f"✗ Error reading backend file: {str(e)}")
    else:
        print(f"✗ Backend file not found at {backend_path}")
        print("Creating backend file...")
        
        # Create the backend file
        backend_content = '''from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.db.models import Q

User = get_user_model()

class EmailOrPhoneBackend(ModelBackend):
    """
    Custom authentication backend that allows users to login with either email or phone number.
    For production, we prioritize email-based authentication.
    """
    
    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None or password is None:
            return None
        
        try:
            # First try to find user by email (preferred for production)
            user = User.objects.get(email=username)
        except User.DoesNotExist:
            try:
                # Fallback to phone number if email not found
                user = User.objects.get(phone_number=username)
            except User.DoesNotExist:
                # Try with username field as well
                try:
                    user = User.objects.get(username=username)
                except User.DoesNotExist:
                    return None
        
        # Check if user is active and password is correct
        if user.check_password(password) and self.user_can_authenticate(user):
            return user
        
        return None'''
        
        try:
            os.makedirs(os.path.dirname(backend_path), exist_ok=True)
            with open(backend_path, 'w') as f:
                f.write(backend_content)
            print("✓ Backend file created successfully")
        except Exception as e:
            print(f"✗ Error creating backend file: {str(e)}")

def main():
    """Main function to check and fix authentication"""
    print("Branch Business Advance Authentication Check and Fix")
    print_separator()
    
    check_settings()
    print_separator()
    
    check_backend_file()
    print_separator()
    
    check_users()
    print_separator()
    
    print("Authentication check and fix completed!")
    print("\nNext steps:")
    print("1. Try logging in with:")
    print("   - admin@branchbusinessadvance.com / admin123")
    print("   - officer@branchbusinessadvance.com / officer123")
    print("   - client@branchbusinessadvance.com / client123")
    print("\n2. If still having issues, check:")
    print("   - Production settings file has AUTHENTICATION_BACKENDS")
    print("   - Users table in database is properly migrated")
    print("   - Web server logs for any errors")

if __name__ == '__main__':
    main() 