import base64
import cv2
import numpy as np
from django.http import JsonResponse
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from ultralytics import YOLO  # YOLOv8 model

# ✅ Load YOLO model once globally
model = YOLO("yolov8n.pt")

@api_view(["POST"])
@permission_classes([AllowAny])
def detect_objects(request):
    """
    Receives a base64-encoded webcam frame from frontend,
    runs YOLOv8 object detection, returns bounding boxes + counts.
    """
    try:
        # ✅ Step 1: Get image data
        image_data = request.data.get("image")
        if not image_data:
            return JsonResponse({"error": "No image provided"}, status=400)

        # ✅ Step 2: Decode base64 image to OpenCV format
        header, encoded = image_data.split(",", 1)
        img_bytes = base64.b64decode(encoded)
        np_arr = np.frombuffer(img_bytes, np.uint8)
        img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)

        if img is None:
            return JsonResponse({"error": "Invalid image data"}, status=400)
        results = model(img)

        detections = []
        label_counts = {}

        for box in results[0].boxes:
            x1, y1, x2, y2 = map(int, box.xyxy[0])
            label = model.names[int(box.cls)]
            conf = float(box.conf)

            # Store detection info
            detections.append({
                "x1": x1,
                "y1": y1,
                "x2": x2,
                "y2": y2,
                "label": label,
                "confidence": round(conf, 2)
            })

            # Count occurrences of each label
            label_counts[label] = label_counts.get(label, 0) + 1

        # ✅ Step 4: Print detections in console
        if detections:
            print(f"Detections: {label_counts} | Total: {len(detections)}")
        else:
            print("No objects detected in this frame")

        # ✅ Step 5: Return detections + count summary
        return JsonResponse({
            "detections": detections,
            "counts_camera": label_counts,
            "total": len(detections)
        })

    except Exception as e:
        print("error in detection:", str(e))
        return JsonResponse({"error": str(e)}, status=500)
