#!/usr/bin/env python
"""
Fix loanscoring model
Makes the user field nullable in the LoanScoring model
"""

import os
import sys
import django
from django.core.management import execute_from_command_line

def setup_django():
    """Setup Django environment"""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
    django.setup()

def fix_loanscoring_model():
    """Fix the LoanScoring model to make user field nullable"""
    print("=== FIXING LOANSCORING MODEL ===")
    
    # Path to the reports models file
    models_file_path = 'reports/models.py'
    
    if os.path.exists(models_file_path):
        try:
            # Read the current models file
            with open(models_file_path, 'r') as f:
                content = f.read()
            
            # Check if the user field is already nullable
            if 'user = models.ForeignKey(' in content and 'null=True' in content:
                print("✓ User field is already nullable in the model")
                return True
            
            # Make the user field nullable
            # Look for the user field definition and add null=True, blank=True
            if 'user = models.ForeignKey(' in content:
                # Replace the user field to make it nullable
                old_user_field = 'user = models.ForeignKey('
                new_user_field = 'user = models.ForeignKey('
                
                # Find the line with the user field and modify it
                lines = content.split('\n')
                modified_lines = []
                
                for line in lines:
                    if 'user = models.ForeignKey(' in line and 'null=True' not in line:
                        # Add null=True, blank=True to the user field
                        if line.strip().endswith(')'):
                            # Remove the closing parenthesis and add null=True, blank=True
                            line = line.rstrip(')') + ', null=True, blank=True)'
                        else:
                            # Add null=True, blank=True before the closing parenthesis
                            line = line.replace(')', ', null=True, blank=True)')
                        print(f"✓ Modified user field: {line.strip()}")
                    modified_lines.append(line)
                
                # Write the modified content back
                modified_content = '\n'.join(modified_lines)
                with open(models_file_path, 'w') as f:
                    f.write(modified_content)
                
                print("✓ Updated LoanScoring model to make user field nullable")
                return True
            else:
                print("⚠ User field not found in the model")
                return False
                
        except Exception as e:
            print(f"⚠ Error modifying models file: {e}")
            return False
    else:
        print("⚠ Models file not found: {models_file_path}")
        return False

def run_migrations():
    """Run migrations after fixing the model"""
    print("\n=== RUNNING MIGRATIONS ===")
    
    try:
        # Run makemigrations
        print("  Running makemigrations...")
        execute_from_command_line(['manage.py', 'makemigrations', '--noinput'])
        print("    ✓ makemigrations completed")
        
        # Run migrate
        print("  Running migrate...")
        execute_from_command_line(['manage.py', 'migrate', '--noinput'])
        print("    ✓ migrate completed")
        
        return True
        
    except Exception as e:
        print(f"    ✗ Migration failed: {e}")
        return False

def main():
    """Main function"""
    print("=== LOANSCORING MODEL FIX ===")
    print("Making the user field nullable in the LoanScoring model.\n")
    
    try:
        setup_django()
        
        # Fix the LoanScoring model
        if fix_loanscoring_model():
            # Run migrations
            if run_migrations():
                print("\n=== FIX COMPLETE ===")
                print("✓ LoanScoring model has been fixed!")
                print("✓ All migrations have been applied successfully!")
                print("✓ Database is up to date")
                print("\n🎉 Your application is ready!")
                print("\n📋 Next steps:")
                print("1. Test your application: python manage.py runserver")
                print("2. Check the portfolio assignment page")
                print("3. Test the enhanced rollover functionality")
                return True
            else:
                print("\n=== MIGRATIONS FAILED ===")
                print("⚠ Model was fixed but migrations failed")
                return False
        else:
            print("\n=== MODEL FIX FAILED ===")
            print("⚠ Could not fix the LoanScoring model")
            return False
        
    except Exception as e:
        print(f"\n❌ Fix failed: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
