"""
State API ViewSet
"""
from rest_framework import viewsets, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend

from flower.viewsets import LimitedModelViewSet
from stateflow import models, services
from stateflow.serializers import (
    StateListSerializer,
    StateDetailSerializer,
    StateCreateUpdateSerializer,
    StateParameterSerializer,
)


class StateViewSet(LimitedModelViewSet):
    """
    状态节点 CRUD 接口
    
    list: 获取状态列表
    retrieve: 获取状态详情（包含参数）
    create: 创建状态
    update: 更新状态
    partial_update: 部分更新状态
    destroy: 删除状态
    
    查询参数:
    - name: 按名称模糊查询
    - search: 全文搜索（名称和描述）
    - ordering: 排序字段，支持 id, name, created_at, updated_at
    """
    queryset = models.State.objects.all()
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['name']
    search_fields = ['name', 'description']
    ordering_fields = ['id', 'name', 'created_at', 'updated_at']
    ordering = ['-created_at']
    
    def get_serializer_class(self):
        """根据动作选择序列化器"""
        if self.action == 'list':
            return StateListSerializer
        elif self.action in ['create', 'update', 'partial_update']:
            return StateCreateUpdateSerializer
        else:  # retrieve
            return StateDetailSerializer
    
    def get_queryset(self):
        """优化查询，retrieve 时预加载参数"""
        queryset = super().get_queryset()
        if self.action == 'retrieve':
            queryset = queryset.prefetch_related('parameters')
        return queryset
    
    @action(detail=True, methods=['get'])
    def parameters(self, request, pk=None):
        """
        获取状态的参数列表
        
        查询参数:
        - required_only: 是否只返回必填参数，默认 false (可选值: true, false)
        """
        state = self.get_object()
        required_only = request.query_params.get('required_only', 'false').lower() == 'true'
        
        parameters = services.get_state_parameters(state, required_only=required_only)
        
        return Response({
            'state_id': state.id,
            'state_name': state.name,
            'parameters': StateParameterSerializer(parameters, many=True).data,
            'count': len(parameters)
        })
