"""
工艺参数 API Views
提供工艺参数的增改查接口（不支持删除）
"""
from rest_framework import viewsets, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.decorators import action
from django.db.models import Q

from flower.viewsets import LimitedModelViewSet
from stateflow.models import StateParameter
from stateflow.serializers import StateParameterSerializer


class StateParameterViewSet(LimitedModelViewSet):
    """
    工艺参数 ViewSet
    
    提供工艺参数的增改查接口，不支持删除操作
    
    Endpoints:
    - GET /api/v1/parameters/ - 获取工艺参数列表
    - POST /api/v1/parameters/ - 创建工艺参数
    - GET /api/v1/parameters/{id}/ - 获取工艺参数详情
    - PUT /api/v1/parameters/{id}/ - 完整更新工艺参数
    - PATCH /api/v1/parameters/{id}/ - 部分更新工艺参数
    """
    queryset = StateParameter.objects.all().order_by('-created_at')
    serializer_class = StateParameterSerializer
    permission_classes = [IsAuthenticated]
    
    # 禁用删除操作
    http_method_names = ['get', 'post', 'put', 'patch', 'head', 'options']
    
    def get_queryset(self):
        """
        可选的查询参数:
        - search: 按 key 或 description 搜索
        - is_required: 筛选必填参数 (true/false)
        - is_image_path: 筛选图片路径参数 (true/false)
        """
        queryset = super().get_queryset()
        
        # 搜索功能
        search = self.request.query_params.get('search', None)
        if search:
            queryset = queryset.filter(
                Q(key__icontains=search) | 
                Q(description__icontains=search)
            )
        
        # 筛选必填参数
        is_required = self.request.query_params.get('is_required', None)
        if is_required is not None:
            is_required_bool = is_required.lower() in ['true', '1', 'yes']
            queryset = queryset.filter(is_required=is_required_bool)
        
        # 筛选图片路径参数
        is_image_path = self.request.query_params.get('is_image_path', None)
        if is_image_path is not None:
            is_image_path_bool = is_image_path.lower() in ['true', '1', 'yes']
            queryset = queryset.filter(is_image_path=is_image_path_bool)
        
        return queryset
    
    def create(self, request, *args, **kwargs):
        """创建工艺参数"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(
            serializer.data,
            status=status.HTTP_201_CREATED,
            headers=headers
        )
    
    def update(self, request, *args, **kwargs):
        """完整更新工艺参数"""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response(serializer.data)
    
    def partial_update(self, request, *args, **kwargs):
        """部分更新工艺参数"""
        kwargs['partial'] = True
        return self.update(request, *args, **kwargs)
    
    def destroy(self, request, *args, **kwargs):
        """禁止删除操作"""
        return Response(
            {'detail': '不允许删除工艺参数'},
            status=status.HTTP_405_METHOD_NOT_ALLOWED
        )
    
    @action(detail=False, methods=['get'])
    def required(self, request):
        """
        获取所有必填参数
        
        GET /api/v1/parameters/required/
        """
        queryset = self.get_queryset().filter(is_required=True)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
    
    @action(detail=False, methods=['get'])
    def optional(self, request):
        """
        获取所有可选参数
        
        GET /api/v1/parameters/optional/
        """
        queryset = self.get_queryset().filter(is_required=False)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
    
    @action(detail=True, methods=['get'])
    def states(self, request, pk=None):
        """
        获取使用该参数的所有状态
        
        GET /api/v1/parameters/{id}/states/
        """
        parameter = self.get_object()
        states = parameter.states.all()
        
        # 简化的状态信息
        states_data = [
            {
                'id': state.id,
                'name': state.name,
                'description': state.description
            }
            for state in states
        ]
        
        return Response({
            'parameter_id': parameter.id,
            'parameter_key': parameter.key,
            'states': states_data,
            'count': len(states_data)
        })
