"""
Process 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 django.db.models import Count

from flower.viewsets import LimitedModelViewSet
from stateflow import models
from stateflow.serializers import (
    ProcessListSerializer,
    ProcessDetailSerializer,
    ProcessCreateUpdateSerializer,
    StateListSerializer,
)


class ProcessViewSet(LimitedModelViewSet):
    """
    流程 CRUD 接口
    
    list: 获取流程列表
    retrieve: 获取流程详情（包含节点）
    create: 创建流程
    update: 更新流程
    partial_update: 部分更新流程
    destroy: 删除流程
    
    查询参数:
    - name: 按名称模糊查询
    - search: 全文搜索（名称和描述）
    - ordering: 排序字段，支持 id, name, node_count, created_at, updated_at
    """
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['name']
    search_fields = ['name', 'description']
    ordering_fields = ['id', 'name', 'node_count', 'created_at', 'updated_at']
    ordering = ['-created_at']
    
    def get_serializer_class(self):
        """根据动作选择序列化器"""
        if self.action == 'list':
            return ProcessListSerializer
        elif self.action in ['create', 'update', 'partial_update']:
            return ProcessCreateUpdateSerializer
        else:  # retrieve
            return ProcessDetailSerializer
    
    def get_queryset(self):
        """优化查询"""
        queryset = models.Process.objects.all()
        
        if self.action == 'list':
            # list 时添加节点计数注解
            queryset = queryset.annotate(node_count=Count('process_nodes'))
        elif self.action == 'retrieve':
            # retrieve 时预加载节点和状态
            queryset = queryset.prefetch_related('process_nodes__state')
        
        return queryset

    @action(detail=True, methods=['get'])
    def nodes(self, request, pk=None):
        """返回指定流程的所有节点列表"""
        process = self.get_object()
        states = process.get_nodes()
        data = StateListSerializer(states, many=True).data
        return Response({
            'process_id': process.id,
            'process_name': process.name,
            'count': len(data),
            'nodes': data,
        })
