#!/usr/bin/env python
"""
Script to test login process and fix secure cookie settings
"""
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, authenticate
from django.conf import settings
from django.test import Client
from django.middleware.csrf import get_token
from django.urls import reverse

User = get_user_model()

def print_separator():
    print("\n" + "=" * 60 + "\n")

def update_session_settings():
    """Update session settings for production"""
    print("Updating Session Settings...")
    
    settings_file = os.path.join('branch_system', 'settings.py')
    production_settings = os.path.join('branch_system', 'settings_production.py')
    
    # Try production settings first
    target_file = production_settings if os.path.exists(production_settings) else settings_file
    
    try:
        with open(target_file, 'r') as f:
            content = f.read()
        
        # Check if settings exist
        settings_to_add = []
        if 'SESSION_COOKIE_SECURE = False' in content:
            content = content.replace('SESSION_COOKIE_SECURE = False', 'SESSION_COOKIE_SECURE = True')
            print("✓ Updated SESSION_COOKIE_SECURE to True")
        elif 'SESSION_COOKIE_SECURE = True' not in content:
            settings_to_add.append('SESSION_COOKIE_SECURE = True')
        
        if 'SESSION_COOKIE_HTTPONLY = True' not in content:
            settings_to_add.append('SESSION_COOKIE_HTTPONLY = True')
        
        if 'SESSION_EXPIRE_AT_BROWSER_CLOSE = True' not in content:
            settings_to_add.append('SESSION_EXPIRE_AT_BROWSER_CLOSE = True')
        
        if settings_to_add:
            # Add new settings at the end of the file
            content += '\n\n# Updated session settings\n' + '\n'.join(settings_to_add)
            print("✓ Added missing session settings")
        
        with open(target_file, 'w') as f:
            f.write(content)
        
        print(f"✓ Settings updated in {target_file}")
        
    except Exception as e:
        print(f"✗ Error updating settings: {str(e)}")

def test_authentication():
    """Test authentication process"""
    print("Testing Authentication Process...")
    
    test_users = [
        ('admin@branchbusinessadvance.com', 'admin123'),
        ('officer@branchbusinessadvance.com', 'officer123'),
        ('client@branchbusinessadvance.com', 'client123')
    ]
    
    for email, password in test_users:
        print(f"\nTesting {email}...")
        
        # 1. Direct authentication
        user = authenticate(username=email, password=password)
        if user:
            print(f"✓ Direct authentication successful")
            print(f"✓ User role: {user.role}")
            print(f"✓ User status: {user.status}")
        else:
            print(f"✗ Direct authentication failed")
        
        # 2. Database check
        try:
            db_user = User.objects.get(email=email)
            print(f"✓ User found in database")
            print(f"✓ Password hash: {db_user.password[:20]}...")
        except User.DoesNotExist:
            print(f"✗ User not found in database")

def check_login_template():
    """Check login template for CSRF and form fields"""
    print("Checking Login Template...")
    
    template_path = os.path.join('templates', 'users', 'login.html')
    try:
        with open(template_path, 'r') as f:
            content = f.read()
            
        # Check for CSRF token
        if '{% csrf_token %}' in content:
            print("✓ CSRF token present in template")
        else:
            print("✗ CSRF token missing from template")
            
        # Check form fields
        if 'name="username"' in content:
            print("✓ Username field present")
        else:
            print("✗ Username field missing")
            
        if 'name="password"' in content:
            print("✓ Password field present")
        else:
            print("✗ Password field missing")
            
        # Check form method
        if 'method="post"' in content.lower():
            print("✓ Form method is POST")
        else:
            print("✗ Form method should be POST")
            
    except Exception as e:
        print(f"✗ Error checking template: {str(e)}")

def fix_template_if_needed():
    """Fix login template if issues found"""
    print("\nChecking if template needs fixes...")
    
    template_path = os.path.join('templates', 'users', 'login.html')
    try:
        with open(template_path, 'r') as f:
            content = f.read()
        
        needs_update = False
        
        # Ensure CSRF token is present
        if '{% csrf_token %}' not in content:
            content = content.replace('<form', '{% csrf_token %}\n<form')
            needs_update = True
            print("✓ Added CSRF token")
        
        # Ensure form fields are correct
        if 'name="username"' not in content:
            content = content.replace('id="id_username"', 'id="id_username" name="username"')
            needs_update = True
            print("✓ Fixed username field")
        
        if 'name="password"' not in content:
            content = content.replace('id="id_password"', 'id="id_password" name="password"')
            needs_update = True
            print("✓ Fixed password field")
        
        if needs_update:
            with open(template_path, 'w') as f:
                f.write(content)
            print("✓ Template updated successfully")
        else:
            print("✓ Template looks good, no fixes needed")
            
    except Exception as e:
        print(f"✗ Error fixing template: {str(e)}")

def main():
    """Main function to test and fix login process"""
    print("Branch Business Advance Login Process Check")
    print_separator()
    
    update_session_settings()
    print_separator()
    
    test_authentication()
    print_separator()
    
    check_login_template()
    print_separator()
    
    fix_template_if_needed()
    print_separator()
    
    print("Login process check completed!")
    print("\nNext steps:")
    print("1. Restart your web server to apply settings changes")
    print("2. Clear your browser cookies and cache")
    print("3. Try logging in with:")
    print("   - admin@branchbusinessadvance.com / admin123")
    print("   - officer@branchbusinessadvance.com / officer123")
    print("   - client@branchbusinessadvance.com / client123")
    print("\nIf still having issues:")
    print("1. Check your web server error logs")
    print("2. Try in an incognito/private browser window")
    print("3. Ensure your site is using HTTPS")

if __name__ == '__main__':
    main() 