from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from allauth.account.adapter import DefaultAccountAdapter
from django.contrib.auth.models import User
from allauth.socialaccount.signals import pre_social_login
from django.dispatch import receiver


class CustomSocialAccountAdapter(DefaultSocialAccountAdapter):
    def is_auto_signup_allowed(self, request, sociallogin):
        """
        Always allow auto signup for social accounts without showing form
        """
        # Always return True to skip the signup form
        return True
    
    def populate_user(self, request, sociallogin, data):
        """
        Populate user information from social account data
        """
        user = super().populate_user(request, sociallogin, data)
        
        # Get email from social account
        email = data.get('email', '')
        if email:
            user.email = email
            
        # Generate username from email if not provided
        if not user.username:
            username = email.split('@')[0] if email else f'user_{sociallogin.account.uid}'
            # Make sure username is unique
            base_username = username
            counter = 1
            while User.objects.filter(username=username).exists():
                username = f"{base_username}{counter}"
                counter += 1
            user.username = username
        
        return user
    
    def save_user(self, request, sociallogin, form=None):
        """
        Save the user and auto-create profile
        """
        user = super().save_user(request, sociallogin, form)
        
        # Create profile if it doesn't exist
        from users.models import Profile
        if not hasattr(user, 'profile'):
            Profile.objects.create(user=user)
        
        return user


class CustomAccountAdapter(DefaultAccountAdapter):
    def is_open_for_signup(self, request):
        """
        Allow signups
        """
        return True


@receiver(pre_social_login)
def link_to_local_user(sender, request, sociallogin, **kwargs):
    """
    If a user with the same email exists, connect the social account to that user
    """
    email_address = sociallogin.account.extra_data.get('email')
    if email_address:
        try:
            user = User.objects.get(email=email_address)
            sociallogin.connect(request, user)
        except User.DoesNotExist:
            pass

