from django.db.models import Q
from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
from rest_framework.parsers import FormParser, MultiPartParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet

from apps.accounts.models import Role
from apps.accounts.permissions import can_manage_organization
from apps.knowledge.models import RoleRagDocument, TrainingFile
from apps.knowledge.serializers import RoleRagDocumentSerializer, TrainingFileSerializer

class TrainingFileViewSet(ModelViewSet):
    queryset = TrainingFile.objects.all()
    serializer_class = TrainingFileSerializer
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]
    lookup_field = 'uuid'
    
    def get_queryset(self):
        user = self.request.user
        queryset = TrainingFile.objects.filter(
            Q(role__organization__owner=user) |
            Q(role__organization__members=user)
        ).distinct()

        organization_uuid = self.request.query_params.get('organization_uuid')
        if organization_uuid in (None, ''):
            organization_uuid = self.request.data.get('organization_uuid')
        if organization_uuid:
            queryset = queryset.filter(role__organization__uuid=organization_uuid)

        role_uuid = self.request.query_params.get('role_uuid')
        if role_uuid in (None, ''):
            role_uuid = self.request.data.get('role_uuid')
        if role_uuid:
            queryset = queryset.filter(role__uuid=role_uuid)

        return queryset

    def perform_create(self, serializer):
        role_uuid = self.request.data.get('role_uuid')
        if not role_uuid:
            raise ValidationError({'role_uuid': 'role_uuid is required.'})

        try:
            role = Role.objects.get(uuid=role_uuid)
        except Role.DoesNotExist:
            raise NotFound('Role not found')

        if not can_manage_organization(self.request.user, role.organization):
            raise PermissionDenied('Permission denied')

        uploaded_file = self.request.FILES.get('file')
        if uploaded_file is None:
            raise ValidationError({'file': 'File is required.'})

        serializer.save(
            uploaded_by=self.request.user,
            role=role,
            file_name=uploaded_file.name,
            file_size=uploaded_file.size,
            file_type=uploaded_file.content_type,
        )

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()

        is_uploader = instance.uploaded_by == request.user
        is_org_owner = instance.role.organization.owner == request.user
        is_org_manager = bool(request.user.is_manager) and instance.role.organization.members.filter(id=request.user.id).exists()

        if not (is_uploader or is_org_owner or is_org_manager):
            raise PermissionDenied('Permission denied')

        return super().destroy(request, *args, **kwargs)

class RoleRagDocumentViewSet(ReadOnlyModelViewSet):
    queryset = RoleRagDocument.objects.all()
    serializer_class = RoleRagDocumentSerializer
    permission_classes = [IsAuthenticated]
    lookup_field = 'uuid'
    
    def get_queryset(self):
        user = self.request.user
        queryset = RoleRagDocument.objects.filter(
            Q(role__organization__owner=user) |
            Q(role__organization__members=user)
        ).distinct()

        organization_uuid = self.request.query_params.get('organization_uuid')
        if organization_uuid in (None, ''):
            organization_uuid = self.request.data.get('organization_uuid')
        if organization_uuid:
            queryset = queryset.filter(role__organization__uuid=organization_uuid)

        role_uuid = self.request.query_params.get('role_uuid')
        if role_uuid in (None, ''):
            role_uuid = self.request.data.get('role_uuid')
        if role_uuid:
            queryset = queryset.filter(role__uuid=role_uuid)

        return queryset
