from rest_framework import status
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from drf_spectacular.utils import extend_schema, OpenApiResponse, OpenApiExample

from api.account.serializers.sensor_serializers import DetectorsResponseSerializer
from sitemanagement.models import Sensor

from api.utils.decorators import handle_exceptions

@extend_schema(tags=['Датчики'])
class SensorView(APIView):
    permission_classes = [IsAuthenticated]
    serializer_class = DetectorsResponseSerializer
    pagination_class = None  # Отключаем пагинацию для получения всех датчиков
    
    @extend_schema(
        summary="Получение всех датчиков",
        description="Получение всех датчиков в формате детекторов",
        responses={200: OpenApiResponse(response=DetectorsResponseSerializer, description="Датчики успешно получены", 
                                        examples=[OpenApiExample(
                                            'Успешный ответ',
                                            value={
                                                
                                                    "id": 1,
                                                    "type": "fire_detector",
                                                    "name": "Датчик 1",
                                                    "object": "Объект 1",
                                                    "status": "warning",
                                                    "zone": "Зона 1",
                                                    "serial_number": "GA-123",
                                                    "floor": 1,
                                                    "notifications": [
                                                        {
                                                            "id": 1,
                                                            "type": "warning",
                                                            "timestamp": "2024-01-15T14:30:00Z",
                                                            "acknowledged": False,
                                                            "priority": "high"
                                                        }
                                                    ]
                                            }
                                        )])})
    @handle_exceptions
    def get(self, request):
        """Получение всех датчиков или датчиков конкретной зоны"""
        try:
            # Получаем опциональный параметр zone_id из query string
            zone_id = request.query_params.get('zone_id', None)
            
            sensors = Sensor.objects.select_related(
                'sensor_type',
                'signal_format'
            ).prefetch_related(
                'zones',
                'zones__object',
                'alerts'
            )
            
            # Фильтруем по зоне если zone_id передан
            if zone_id:
                sensors = sensors.filter(zones__id=zone_id)
                print(f"[SensorView] Filtering by zone_id: {zone_id}")
            
            sensors = sensors.all()
            
            total_count = sensors.count()
            print(f"[SensorView] Total sensors in DB: {total_count}")
            
            # Проверяем уникальность serial_number
            serial_numbers = [s.serial_number for s in sensors if s.serial_number]
            unique_serials = set(serial_numbers)
            print(f"[SensorView] Unique serial_numbers: {len(unique_serials)} out of {len(serial_numbers)}")
            
            if len(serial_numbers) != len(unique_serials):
                from collections import Counter
                duplicates = {k: v for k, v in Counter(serial_numbers).items() if v > 1}
                print(f"[SensorView] WARNING: Found duplicate serial_numbers: {duplicates}")
            
            serializer = DetectorsResponseSerializer(sensors)
            detectors_dict = serializer.data.get('detectors', {})
            
            print(f"[SensorView] Serialized detectors count: {len(detectors_dict)}")
            print(f"[SensorView] Sample detector_ids: {list(detectors_dict.keys())[:5]}")
            
            return Response(serializer.data, status=status.HTTP_200_OK)
        except Sensor.DoesNotExist:
            return Response(
                {"error": "Датчики не найдены"}, 
                status=status.HTTP_404_NOT_FOUND)
