"""
YOLO Object Detection Model for Property Verification

YOLOv8 (You Only Look Once) is a state-of-the-art object detection model that:
1. Divides the image into a grid
2. Predicts bounding boxes and class probabilities for each grid cell
3. Detects multiple objects in a single forward pass (very fast)
4. Returns detected objects with confidence scores

We use YOLOv8n (nano) - the smallest and fastest variant, perfect for real-time applications.
It's trained on the COCO dataset which includes 80 common object classes.
"""

from ultralytics import YOLO
from PIL import Image
import numpy as np
from typing import List, Dict, Tuple
import logging

# Fix the import path issue
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from config import YOLO_MODEL, PROPERTY_OBJECTS

logger = logging.getLogger(__name__)


class YOLODetector:
    """
    YOLO-based object detector for identifying property-related objects in images.
    """
    
    def __init__(self):
        """
        Initialize the YOLO model.
        The model will be downloaded automatically on first run.
        """
        try:
            logger.info(f"Loading YOLO model: {YOLO_MODEL}")
            self.model = YOLO(YOLO_MODEL)
            self.property_objects = set(PROPERTY_OBJECTS)
            logger.info("YOLO model loaded successfully")
        except Exception as e:
            logger.error(f"Failed to load YOLO model: {e}")
            raise
    
    def detect_objects(self, image_path: str) -> Tuple[bool, List[Dict], List[str]]:
        """
        Detect objects in an image and determine if it contains property-related items.
        
        Args:
            image_path: Path to the image file
            
        Returns:
            Tuple containing:
            - is_valid: Boolean indicating if property objects were detected
            - detections: List of all detected objects with confidence scores
            - property_objects_found: List of property-related objects found
        """
        try:
            # Run YOLO inference
            # verbose=False suppresses detailed output
            results = self.model(image_path, verbose=False)
            
            detections = []
            property_objects_found = []
            
            # Process detection results
            for result in results:
                # Get class names and confidence scores
                boxes = result.boxes
                
                for box in boxes:
                    # Extract detection information
                    class_id = int(box.cls[0])
                    confidence = float(box.conf[0])
                    class_name = result.names[class_id]
                    
                    # Store detection info
                    detection_info = {
                        "object": class_name,
                        "confidence": round(confidence, 3)
                    }
                    detections.append(detection_info)
                    
                    # Check if this is a property-related object
                    if class_name.lower() in self.property_objects:
                        property_objects_found.append(class_name)
                        logger.info(f"Property object detected: {class_name} (confidence: {confidence:.3f})")
            
            # Image is valid if any property objects were found
            is_valid = len(property_objects_found) > 0
            
            logger.info(f"YOLO Detection - Valid: {is_valid}, Objects found: {property_objects_found}")
            
            return is_valid, detections, property_objects_found
            
        except Exception as e:
            logger.error(f"Error during YOLO detection: {e}")
            return False, [], []
    
    def get_model_info(self) -> Dict:
        """
        Get information about the loaded YOLO model.
        """
        return {
            "model_name": YOLO_MODEL,
            "property_objects": list(self.property_objects),
            "total_classes": len(self.model.names) if hasattr(self.model, 'names') else 80
        }