#!/usr/bin/env python3
"""
Test script to debug PortfolioAssignment creation
"""

import os
import sys
import django
from django.db import connection

def setup_django():
    """Setup Django environment"""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
    django.setup()

def test_portfolio_assignment():
    """Test creating a PortfolioAssignment record"""
    
    print("🔧 Testing PortfolioAssignment creation...")
    
    try:
        from users.models import CustomUser, PortfolioAssignment
        
        # Get a test client and manager
        client = CustomUser.objects.filter(role='borrower').first()
        manager = CustomUser.objects.filter(role__in=['loan_officer', 'team_leader']).first()
        
        if not client:
            print("❌ No borrower found")
            return False
            
        if not manager:
            print("❌ No loan officer/team leader found")
            return False
            
        print(f"✅ Found client: {client.get_full_name()}")
        print(f"✅ Found manager: {manager.get_full_name()}")
        
        # Try to create a PortfolioAssignment
        print("🔧 Creating PortfolioAssignment...")
        
        assignment = PortfolioAssignment.objects.create(
            client=client,
            portfolio_manager=manager,
            assigned_by=manager,
            reason="Test assignment"
        )
        
        print(f"✅ Successfully created assignment with ID: {assignment.id}")
        print(f"✅ Assignment details: {assignment}")
        
        # Clean up
        assignment.delete()
        print("✅ Test assignment deleted")
        
        return True
        
    except Exception as e:
        print(f"❌ Error creating assignment: {e}")
        import traceback
        traceback.print_exc()
        return False

def check_table_structure():
    """Check the actual table structure"""
    
    print("\n🔧 Checking table structure...")
    
    with connection.cursor() as cursor:
        # Check table structure
        cursor.execute("DESCRIBE portfolio_assignments")
        columns = cursor.fetchall()
        
        print("Table structure:")
        for col in columns:
            print(f"  {col[0]}: {col[1]} {col[2]} {col[3]} {col[4]}")
        
        # Check auto_increment value
        cursor.execute("SHOW TABLE STATUS LIKE 'portfolio_assignments'")
        result = cursor.fetchone()
        if result:
            auto_increment = result[10]
            print(f"\nAuto_increment value: {auto_increment}")

def main():
    """Main function"""
    print("🔧 PORTFOLIO ASSIGNMENT TEST")
    print("=" * 50)
    
    try:
        setup_django()
        print("✅ Django environment setup complete")
        
        check_table_structure()
        
        if test_portfolio_assignment():
            print("\n🎉 PortfolioAssignment creation works!")
        else:
            print("\n❌ PortfolioAssignment creation failed!")
            
    except Exception as e:
        print(f"\n❌ Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()
