from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from .models import Policy, PolicySection
from .serializers import PolicySerializer, PolicyListSerializer


class PolicyViewSet(viewsets.ReadOnlyModelViewSet):
    """
    ViewSet for viewing policies.
    Provides list and retrieve actions.
    """
    queryset = Policy.objects.filter(is_active=True)
    
    def get_serializer_class(self):
        if self.action == 'list':
            return PolicyListSerializer
        return PolicySerializer
    
    def get_queryset(self):
        queryset = Policy.objects.filter(is_active=True)
        policy_type = self.request.query_params.get('type', None)
        
        if policy_type:
            queryset = queryset.filter(type=policy_type)
        
        return queryset
    
    def retrieve(self, request, pk=None):
        """
        Retrieve a policy by ID or type
        """
        # Try to get by ID first
        if pk.isdigit():
            policy = get_object_or_404(Policy, pk=pk, is_active=True)
        else:
            # Otherwise try by type (slug)
            policy = get_object_or_404(Policy, type=pk, is_active=True)
        
        serializer = self.get_serializer(policy)
        return Response(serializer.data)
    
    @action(detail=False, methods=['get'], url_path='by-type/(?P<policy_type>[^/.]+)')
    def by_type(self, request, policy_type=None):
        """
        Get a specific policy by its type
        """
        policy = get_object_or_404(Policy, type=policy_type, is_active=True)
        serializer = PolicySerializer(policy)
        return Response(serializer.data)

