"""
Migration script to convert single role to multiple roles.

This script should be run AFTER:
1. Running: python manage.py makemigrations appauthentication
2. Running: python manage.py migrate appauthentication

Usage:
    python migrate_roles.py
"""

import os
import django

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

from appauthentication.models import UserProfile, Role


def create_default_roles():
    """Create the default roles if they don't exist"""
    roles_to_create = [
        ('sponsor', 'Sponsor'),
        ('guardian', 'Guardian'),
        ('admin', 'Administrator'),
    ]
    
    print("Creating default roles...")
    for role_name, role_display in roles_to_create:
        role, created = Role.objects.get_or_create(
            name=role_name,
            defaults={'description': f'{role_display} role'}
        )
        if created:
            print(f"  ✓ Created role: {role_display}")
        else:
            print(f"  - Role already exists: {role_display}")
    print()


def migrate_user_profiles():
    """Migrate existing user profiles to use the new many-to-many roles"""
    print("Migrating user profiles...")
    
    profiles = UserProfile.objects.all()
    migrated_count = 0
    skipped_count = 0
    
    for profile in profiles:
        # Check if the old 'role' field exists and has a value
        if hasattr(profile, 'role') and profile.role:
            try:
                # Get or create the role
                role, created = Role.objects.get_or_create(
                    name=profile.role,
                    defaults={'description': f'{profile.get_role_display()} role'}
                )
                
                # Add the role to the user's roles (if not already added)
                if not profile.roles.filter(name=profile.role).exists():
                    profile.roles.add(role)
                    print(f"  ✓ Migrated {profile.user.username}: {profile.role} → {role.get_name_display()}")
                    migrated_count += 1
                else:
                    print(f"  - Already migrated: {profile.user.username}")
                    skipped_count += 1
            except Exception as e:
                print(f"  ✗ Error migrating {profile.user.username}: {e}")
        else:
            # If no old role, assign default 'sponsor' role
            try:
                sponsor_role, created = Role.objects.get_or_create(
                    name='sponsor',
                    defaults={'description': 'Sponsor role'}
                )
                if not profile.roles.exists():
                    profile.roles.add(sponsor_role)
                    print(f"  ✓ Assigned default sponsor role to {profile.user.username}")
                    migrated_count += 1
                else:
                    print(f"  - {profile.user.username} already has roles: {profile.get_roles_display()}")
                    skipped_count += 1
            except Exception as e:
                print(f"  ✗ Error assigning default role to {profile.user.username}: {e}")
    
    print(f"\nMigration complete! Migrated: {migrated_count}, Skipped: {skipped_count}")


def main():
    print("=" * 60)
    print("User Role Migration Script")
    print("=" * 60)
    print()
    
    # Step 1: Create default roles
    create_default_roles()
    
    # Step 2: Migrate existing user profiles
    migrate_user_profiles()
    
    print()
    print("=" * 60)
    print("Migration completed successfully!")
    print("=" * 60)
    print()
    print("Next steps:")
    print("1. Review the migrated data in the admin panel")
    print("2. You can now remove the old 'role' field from the model if it still exists")
    print("3. Run: python manage.py makemigrations appauthentication")
    print("4. Run: python manage.py migrate appauthentication")
    print()


if __name__ == '__main__':
    main()
