from rest_framework import generics, status, permissions, viewsets # 确保 viewsets 导入
from rest_framework.decorators import action # 如果有自定义action，虽然这里目前没有用到
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from django.db.models import Count, Q # 确保 Q 和 Count 导入

from .models import CustomUser, InterestTag # <<<< 导入 InterestTag 和 CustomUser
from .serializers import (
    UserRegistrationSerializer, 
    UserProfileSerializer, 
    InterestTagSerializer, # <<<< 导入 InterestTagSerializer
    RecommendedUserSerializer # <<<< 导入 RecommendedUserSerializer
)

class UserRegistrationView(generics.CreateAPIView):
    queryset = CustomUser.objects.all()
    serializer_class = UserRegistrationSerializer
    permission_classes = [permissions.AllowAny]

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        refresh = RefreshToken.for_user(user)
        user_data = UserProfileSerializer(user, context={'request': request}).data
        response_data = {
            'refresh': str(refresh),
            'access': str(refresh.access_token),
            'user': user_data
        }
        return Response(response_data, status=status.HTTP_201_CREATED)

class UserProfileView(generics.RetrieveUpdateAPIView):
    queryset = CustomUser.objects.all()
    serializer_class = UserProfileSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_object(self):
        return self.request.user

# --- 从 groups/views.py 移动过来的 ---
class InterestTagViewSet(viewsets.ReadOnlyModelViewSet): # 应该在 accounts/views.py
    """
    一个只读的ViewSet，用于查看兴趣标签列表和详情。
    """
    queryset = InterestTag.objects.all().order_by('name') # InterestTag 现在已导入
    serializer_class = InterestTagSerializer           # InterestTagSerializer 现在已导入
    permission_classes = [permissions.AllowAny]

class RecommendedUserListView(generics.ListAPIView): # 应该在 accounts/views.py
    """
    获取与当前登录用户有共同兴趣的推荐用户列表。
    """
    serializer_class = RecommendedUserSerializer # RecommendedUserSerializer 现在已导入
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        current_user = self.request.user # CustomUser 现在已导入
        current_user_interest_ids = list(current_user.interests.values_list('id', flat=True))

        if not current_user_interest_ids:
            return CustomUser.objects.none()

        recommended_users = CustomUser.objects.filter(
            interests__id__in=current_user_interest_ids
        ).exclude(
            id=current_user.id
        ).distinct()

        recommended_users = recommended_users.annotate(
            common_interest_count=Count(
                'interests', 
                filter=Q(interests__id__in=current_user_interest_ids)
            )
        ).order_by('-common_interest_count', '?')

        current_user_interests_set = set(current_user.interests.all())
        for user_obj in recommended_users:
            user_interests_set = set(user_obj.interests.all())
            common_tags = list(current_user_interests_set.intersection(user_interests_set))
            user_obj.common_interests_list = common_tags
            
        return recommended_users