#!/usr/bin/env python
import os
import sys
import django

# Setup Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import RequestFactory, Client
from django.contrib.auth import get_user_model
from users.models import CustomUser, PortfolioAssignment
from django.utils import timezone
from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.auth.middleware import AuthenticationMiddleware

def debug_assignment():
    """Debug the portfolio assignment issue"""
    
    print("=== Debugging Portfolio Assignment ===\n")
    
    # Create a test client
    client = Client()
    
    # Get or create a test user with appropriate permissions
    User = get_user_model()
    test_user = User.objects.filter(
        role__in=['admin', 'team_leader', 'manager']
    ).first()
    
    if not test_user:
        print("ERROR: No admin/manager user found for testing!")
        return
    
    print(f"Using test user: {test_user.get_full_name()} ({test_user.role})")
    
    # Login the user
    client.force_login(test_user)
    
    # Get an unassigned client and a portfolio manager
    unassigned_client = CustomUser.objects.filter(
        role='borrower',
        status='active',
        portfolio_manager__isnull=True
    ).first()
    
    portfolio_manager = CustomUser.objects.filter(
        role__in=['loan_officer', 'team_leader', 'manager'],
        status='active'
    ).first()
    
    if not unassigned_client or not portfolio_manager:
        print("ERROR: No unassigned client or portfolio manager found!")
        return
    
    print(f"Testing assignment:")
    print(f"  Client: {unassigned_client.get_full_name()} ({unassigned_client.id})")
    print(f"  Manager: {portfolio_manager.get_full_name()} ({portfolio_manager.id})")
    print(f"  Client role: {unassigned_client.role}")
    print(f"  Client status: {unassigned_client.status}")
    print(f"  Client portfolio_manager: {unassigned_client.portfolio_manager}")
    print(f"  Manager role: {portfolio_manager.role}")
    print(f"  Manager status: {portfolio_manager.status}")
    
    # Test the assignment POST with detailed debugging
    try:
        # First, get the page to get CSRF token
        get_response = client.get('/portfolio/assign/')
        print(f"GET response status: {get_response.status_code}")
        
        if get_response.status_code != 200:
            print("ERROR: Could not get assignment page!")
            return
        
        # Extract CSRF token
        csrf_token = None
        content = get_response.content.decode('utf-8')
        if 'csrfmiddlewaretoken' in content:
            import re
            csrf_match = re.search(r'name="csrfmiddlewaretoken" value="([^"]+)"', content)
            if csrf_match:
                csrf_token = csrf_match.group(1)
                print(f"CSRF token found: {csrf_token[:20]}...")
            else:
                print("WARNING: CSRF token not found in form!")
        else:
            print("WARNING: No CSRF token in response!")
        
        # Prepare POST data
        post_data = {
            'client_ids': [str(unassigned_client.id)],
            'manager_id': str(portfolio_manager.id),
            'assignment_type': 'manual'
        }
        
        if csrf_token:
            post_data['csrfmiddlewaretoken'] = csrf_token
        
        print(f"POST data: {post_data}")
        
        # Make the POST request
        response = client.post('/portfolio/assign/', post_data)
        
        print(f"POST response status: {response.status_code}")
        
        if response.status_code == 302:
            print("SUCCESS: Assignment POST successful (redirected)!")
            
            # Check if assignment was created
            assignments_after = PortfolioAssignment.objects.filter(
                client=unassigned_client,
                is_active=True
            ).count()
            
            print(f"  Assignments after: {assignments_after}")
            
            if assignments_after > 0:
                print("SUCCESS: New assignment record created!")
                
                # Check if client's portfolio_manager was updated
                updated_client = CustomUser.objects.get(id=unassigned_client.id)
                if updated_client.portfolio_manager == portfolio_manager:
                    print("SUCCESS: Client portfolio_manager field updated!")
                else:
                    print("ERROR: Client portfolio_manager field not updated!")
                    
            else:
                print("ERROR: No new assignment record created!")
                
        else:
            print(f"ERROR: Assignment POST failed with status {response.status_code}")
            if hasattr(response, 'content'):
                content = response.content.decode('utf-8')
                print(f"Response content: {content[:500]}...")
                
    except Exception as e:
        print(f"ERROR: Exception occurred during assignment: {str(e)}")
        import traceback
        traceback.print_exc()
    
    print("\n=== Debug Complete ===")

if __name__ == "__main__":
    debug_assignment()
