"""
Image Analysis Service using OpenCV and other Python libraries
Handles object detection, face detection, and other image processing tasks
"""
import cv2
import numpy as np
import base64
from PIL import Image
from io import BytesIO
import logging
from ultralytics import YOLO
import torch

logger = logging.getLogger(__name__)

class ImageAnalysisService:
    
    def __init__(self):
        """Initialize the image analysis service with pre-trained models"""
        self.face_cascade = None
        self.yolo_model = None
        self._load_models()
    
    def _load_models(self):
        """Load pre-trained models for detection"""
        try:
            # Load OpenCV face cascade
            self.face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
            logger.info("✅ Face detection model loaded successfully")
        except Exception as e:
            logger.error(f"❌ Error loading face detection model: {e}")
            
        try:
            # Load YOLO model for object detection
            logger.info("🔄 Loading YOLO model...")
            self.yolo_model = YOLO('yolov8n.pt')  # nano version for speed
            logger.info("✅ YOLO model loaded successfully")
        except Exception as e:
            logger.error(f"❌ Error loading YOLO model: {e}")
            self.yolo_model = None
    
    def analyze_image(self, image_base64: str) -> dict:
        """
        Analyze image for objects, faces, and other features
        
        Args:
            image_base64: Base64 encoded image string
            
        Returns:
            dict: Analysis results containing detected objects, faces, etc.
        """
        try:
            # Decode base64 image
            image = self._decode_base64_image(image_base64)
            if image is None:
                return {'error': 'Invalid image data'}
            
            # Convert PIL to OpenCV format
            cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
            
            # Get image info first
            image_info = self._get_image_info(image)
            logger.info(f"📊 Analyzing image: {image_info['width']}x{image_info['height']}, {image_info.get('format', 'unknown')} format")
            
            # Perform various analyses
            faces = self._detect_faces(cv_image)
            logger.info(f"👤 Face detection: {len(faces)} faces found")
            
            objects = self._detect_objects(cv_image)
            logger.info(f"🔍 Object detection: {len(objects)} objects found")
            
            # Log object details for debugging
            for i, obj in enumerate(objects[:3]):  # Log first 3 objects
                logger.info(f"   Object {i+1}: {obj['type']} (confidence: {obj['confidence']:.2f}, method: {obj.get('detection_method', 'unknown')})")
            
            motion_areas = self._detect_motion_areas(cv_image)
            colors = self._analyze_colors(cv_image)
            
            results = {
                'success': True,
                'image_info': image_info,
                'faces': faces,
                'objects': objects,
                'motion_areas': motion_areas,
                'colors': colors,
                'timestamp': self._get_timestamp()
            }
            
            logger.info(f"✅ Image analysis completed: {len(results['faces'])} faces, {len(results['objects'])} objects")
            return results
            
        except Exception as e:
            logger.error(f"❌ Error analyzing image: {e}")
            return {'error': f'Analysis failed: {str(e)}', 'success': False}
    
    def _decode_base64_image(self, image_base64: str) -> Image.Image:
        """Decode base64 string to PIL Image"""
        try:
            # Remove data URL prefix if present
            if ',' in image_base64:
                image_base64 = image_base64.split(',')[1]
            
            # Decode base64
            image_data = base64.b64decode(image_base64)
            image = Image.open(BytesIO(image_data))
            return image.convert('RGB')
        except Exception as e:
            logger.error(f"Error decoding base64 image: {e}")
            return None
    
    def _get_image_info(self, image: Image.Image) -> dict:
        """Get basic image information"""
        return {
            'width': image.width,
            'height': image.height,
            'format': image.format,
            'mode': image.mode,
            'size_bytes': len(image.tobytes())
        }
    
    def _detect_faces(self, cv_image: np.ndarray) -> list:
        """Detect faces in the image using OpenCV"""
        try:
            if self.face_cascade is None:
                return []
            
            # Convert to grayscale for face detection
            gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
            
            # Detect faces
            faces = self.face_cascade.detectMultiScale(
                gray,
                scaleFactor=1.1,
                minNeighbors=5,
                minSize=(30, 30)
            )
            
            # Convert to list of dictionaries
            face_list = []
            for (x, y, w, h) in faces:
                face_list.append({
                    'type': 'face',
                    'confidence': 0.8,  # OpenCV doesn't provide confidence for Haar cascades
                    'bounding_box': {
                        'x': int(x),
                        'y': int(y),
                        'width': int(w),
                        'height': int(h)
                    }
                })
            
            return face_list
        except Exception as e:
            logger.error(f"Error detecting faces: {e}")
            return []
    
    def _detect_objects(self, cv_image: np.ndarray) -> list:
        """Detect objects in the image using YOLO pre-trained model"""
        try:
            objects = []
            
            # Use YOLO for real-world object detection
            if self.yolo_model is not None:
                yolo_objects = self._detect_yolo_objects(cv_image)
                objects.extend(yolo_objects)
            else:
                logger.warning("YOLO model not available, falling back to basic detection")
                # Fallback to basic detection methods
                contour_objects = self._detect_contour_objects(cv_image)
                objects.extend(contour_objects)
                
                template_objects = self._detect_template_objects(cv_image)
                objects.extend(template_objects)
                
                color_objects = self._detect_color_objects(cv_image)
                objects.extend(color_objects)
            
            # Remove duplicates and sort by confidence
            objects = self._remove_duplicate_objects(objects)
            objects.sort(key=lambda x: x['confidence'], reverse=True)
            
            # Limit to top 15 objects for better coverage
            return objects[:15]
            
        except Exception as e:
            logger.error(f"Error detecting objects: {e}")
            return []
    
    def _detect_yolo_objects(self, cv_image: np.ndarray) -> list:
        """Detect real-world objects using YOLO pre-trained model"""
        try:
            objects = []
            
            # Run YOLO inference
            results = self.yolo_model(cv_image, verbose=False)
            
            # Process results
            for result in results:
                boxes = result.boxes
                if boxes is not None:
                    for box in boxes:
                        # Get bounding box coordinates
                        x1, y1, x2, y2 = box.xyxy[0].cpu().numpy()
                        
                        # Get confidence and class
                        confidence = float(box.conf[0].cpu().numpy())
                        class_id = int(box.cls[0].cpu().numpy())
                        
                        # Get class name from YOLO model
                        class_name = self.yolo_model.names[class_id]
                        
                        # Only include objects with reasonable confidence
                        if confidence > 0.3:  # 30% confidence threshold
                            objects.append({
                                'type': class_name,
                                'confidence': confidence,
                                'bounding_box': {
                                    'x': int(x1),
                                    'y': int(y1),
                                    'width': int(x2 - x1),
                                    'height': int(y2 - y1)
                                },
                                'area': int((x2 - x1) * (y2 - y1)),
                                'detection_method': 'yolo'
                            })
            
            logger.info(f"🎯 YOLO detected {len(objects)} objects")
            return objects
            
        except Exception as e:
            logger.error(f"❌ Error in YOLO detection: {e}")
            return []
    
    def _detect_contour_objects(self, cv_image: np.ndarray) -> list:
        """Detect objects using contour detection with improved sensitivity"""
        try:
            # Convert to grayscale
            gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
            
            # Apply multiple preprocessing techniques
            # 1. Gaussian blur
            blurred = cv2.GaussianBlur(gray, (3, 3), 0)
            
            # 2. Adaptive thresholding for better edge detection
            adaptive_thresh = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
            
            # 3. Multiple edge detection approaches
            edges1 = cv2.Canny(blurred, 30, 100)  # Lower thresholds for more edges
            edges2 = cv2.Canny(adaptive_thresh, 50, 150)
            
            # Combine edge maps
            edges = cv2.bitwise_or(edges1, edges2)
            
            # Morphological operations to close gaps
            kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
            edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)
            
            # Find contours
            contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            
            objects = []
            image_area = cv_image.shape[0] * cv_image.shape[1]
            min_area = max(500, image_area * 0.001)  # Dynamic minimum area (0.1% of image)
            max_area = image_area * 0.8  # Maximum 80% of image
            
            for contour in contours:
                area = cv2.contourArea(contour)
                if min_area < area < max_area:
                    # Get bounding rectangle
                    x, y, w, h = cv2.boundingRect(contour)
                    
                    # Skip objects that are too thin or at image edges
                    if w < 10 or h < 10:
                        continue
                    if x < 5 or y < 5 or x + w > cv_image.shape[1] - 5 or y + h > cv_image.shape[0] - 5:
                        continue
                    
                    # Calculate confidence based on multiple factors
                    perimeter = cv2.arcLength(contour, True)
                    if perimeter == 0:
                        continue
                        
                    # Circularity measure
                    circularity = 4 * np.pi * area / (perimeter * perimeter)
                    
                    # Aspect ratio
                    aspect_ratio = w / h
                    
                    # Extent (contour area / bounding box area)
                    extent = area / (w * h)
                    
                    # Calculate confidence (0.3 to 0.9)
                    size_factor = min(1.0, area / (image_area * 0.1))
                    shape_factor = min(circularity, extent)
                    confidence = 0.3 + (size_factor * 0.4) + (shape_factor * 0.2)
                    
                    # Classify object type
                    object_type = self._classify_object_by_shape(contour, area)
                    
                    objects.append({
                        'type': object_type,
                        'confidence': min(0.9, confidence),
                        'bounding_box': {
                            'x': int(x),
                            'y': int(y),
                            'width': int(w),
                            'height': int(h)
                        },
                        'area': int(area),
                        'detection_method': 'contour'
                    })
            
            return objects
            
        except Exception as e:
            logger.error(f"Error in contour detection: {e}")
            return []
    
    def _detect_template_objects(self, cv_image: np.ndarray) -> list:
        """Detect common objects using simple template matching"""
        try:
            objects = []
            gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
            
            # Create simple geometric templates
            templates = self._create_simple_templates()
            
            for template_name, template in templates.items():
                # Multi-scale template matching
                for scale in [0.5, 0.7, 1.0, 1.3, 1.5]:
                    scaled_template = cv2.resize(template, None, fx=scale, fy=scale)
                    if scaled_template.shape[0] > gray.shape[0] or scaled_template.shape[1] > gray.shape[1]:
                        continue
                    
                    # Template matching
                    result = cv2.matchTemplate(gray, scaled_template, cv2.TM_CCOEFF_NORMED)
                    locations = np.where(result >= 0.3)  # Lower threshold for more detections
                    
                    for pt in zip(*locations[::-1]):
                        h, w = scaled_template.shape
                        confidence = float(result[pt[1], pt[0]])
                        
                        objects.append({
                            'type': f'{template_name}_template',
                            'confidence': confidence,
                            'bounding_box': {
                                'x': int(pt[0]),
                                'y': int(pt[1]),
                                'width': int(w),
                                'height': int(h)
                            },
                            'area': int(w * h),
                            'detection_method': 'template'
                        })
            
            return objects
            
        except Exception as e:
            logger.error(f"Error in template detection: {e}")
            return []
    
    def _detect_color_objects(self, cv_image: np.ndarray) -> list:
        """Detect objects based on distinct color regions"""
        try:
            objects = []
            
            # Convert to HSV for better color segmentation
            hsv = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV)
            
            # Define color ranges for common objects
            color_ranges = {
                'red_object': [(0, 50, 50), (10, 255, 255)],
                'blue_object': [(100, 50, 50), (130, 255, 255)],
                'green_object': [(40, 50, 50), (80, 255, 255)],
                'yellow_object': [(20, 50, 50), (40, 255, 255)],
            }
            
            for color_name, (lower, upper) in color_ranges.items():
                # Create mask for color range
                mask = cv2.inRange(hsv, np.array(lower), np.array(upper))
                
                # Morphological operations to clean up the mask
                kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
                mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
                mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
                
                # Find contours in the mask
                contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
                
                for contour in contours:
                    area = cv2.contourArea(contour)
                    if area > 1000:  # Minimum area for color objects
                        x, y, w, h = cv2.boundingRect(contour)
                        
                        # Calculate confidence based on area and color consistency
                        mask_area = cv2.countNonZero(mask[y:y+h, x:x+w])
                        color_consistency = mask_area / (w * h)
                        confidence = min(0.8, color_consistency * 0.6 + (area / 10000) * 0.4)
                        
                        if confidence > 0.3:
                            objects.append({
                                'type': color_name,
                                'confidence': confidence,
                                'bounding_box': {
                                    'x': int(x),
                                    'y': int(y),
                                    'width': int(w),
                                    'height': int(h)
                                },
                                'area': int(area),
                                'detection_method': 'color'
                            })
            
            return objects
            
        except Exception as e:
            logger.error(f"Error in color detection: {e}")
            return []
    
    def _create_simple_templates(self) -> dict:
        """Create simple geometric templates for object detection"""
        templates = {}
        
        # Circle template
        circle_template = np.zeros((50, 50), dtype=np.uint8)
        cv2.circle(circle_template, (25, 25), 20, 255, 2)
        templates['circle'] = circle_template
        
        # Rectangle template
        rect_template = np.zeros((40, 60), dtype=np.uint8)
        cv2.rectangle(rect_template, (5, 5), (55, 35), 255, 2)
        templates['rectangle'] = rect_template
        
        # Triangle template
        triangle_template = np.zeros((50, 50), dtype=np.uint8)
        points = np.array([[25, 5], [5, 45], [45, 45]], np.int32)
        cv2.polylines(triangle_template, [points], True, 255, 2)
        templates['triangle'] = triangle_template
        
        return templates
    
    def _remove_duplicate_objects(self, objects: list) -> list:
        """Remove overlapping duplicate objects"""
        if not objects:
            return objects
        
        # Sort by confidence (highest first)
        objects.sort(key=lambda x: x['confidence'], reverse=True)
        
        filtered_objects = []
        for obj in objects:
            is_duplicate = False
            obj_box = obj['bounding_box']
            
            for existing_obj in filtered_objects:
                existing_box = existing_obj['bounding_box']
                
                # Calculate overlap
                overlap = self._calculate_box_overlap(obj_box, existing_box)
                if overlap > 0.5:  # 50% overlap threshold
                    is_duplicate = True
                    break
            
            if not is_duplicate:
                filtered_objects.append(obj)
        
        return filtered_objects
    
    def _calculate_box_overlap(self, box1: dict, box2: dict) -> float:
        """Calculate overlap ratio between two bounding boxes"""
        try:
            # Calculate intersection
            x1 = max(box1['x'], box2['x'])
            y1 = max(box1['y'], box2['y'])
            x2 = min(box1['x'] + box1['width'], box2['x'] + box2['width'])
            y2 = min(box1['y'] + box1['height'], box2['y'] + box2['height'])
            
            if x2 <= x1 or y2 <= y1:
                return 0.0
            
            intersection = (x2 - x1) * (y2 - y1)
            area1 = box1['width'] * box1['height']
            area2 = box2['width'] * box2['height']
            union = area1 + area2 - intersection
            
            return intersection / union if union > 0 else 0.0
            
        except Exception:
            return 0.0
    
    def _classify_object_by_shape(self, contour, area) -> str:
        """Simple object classification based on contour shape"""
        try:
            # Calculate aspect ratio
            x, y, w, h = cv2.boundingRect(contour)
            aspect_ratio = w / h
            
            # Calculate extent (contour area / bounding box area)
            extent = area / (w * h)
            
            # Simple classification rules
            if 0.8 <= aspect_ratio <= 1.2 and extent > 0.7:
                return "circular_object"
            elif aspect_ratio > 2:
                return "horizontal_object"
            elif aspect_ratio < 0.5:
                return "vertical_object"
            elif extent > 0.8:
                return "rectangular_object"
            else:
                return "irregular_object"
                
        except Exception:
            return "unknown_object"
    
    def _detect_motion_areas(self, cv_image: np.ndarray) -> list:
        """Detect areas of potential motion (placeholder for now)"""
        # This would typically compare with previous frame
        # For now, return empty list
        return []
    
    def _analyze_colors(self, cv_image: np.ndarray) -> dict:
        """Analyze dominant colors in the image"""
        try:
            # Convert BGR to RGB
            rgb_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
            
            # Reshape image to be a list of pixels
            pixels = rgb_image.reshape(-1, 3)
            
            # Calculate mean color
            mean_color = np.mean(pixels, axis=0)
            
            # Calculate color histogram
            hist_r = cv2.calcHist([rgb_image], [0], None, [256], [0, 256])
            hist_g = cv2.calcHist([rgb_image], [1], None, [256], [0, 256])
            hist_b = cv2.calcHist([rgb_image], [2], None, [256], [0, 256])
            
            # Find dominant colors (simplified)
            dominant_r = np.argmax(hist_r)
            dominant_g = np.argmax(hist_g)
            dominant_b = np.argmax(hist_b)
            
            return {
                'mean_color': {
                    'r': int(mean_color[0]),
                    'g': int(mean_color[1]),
                    'b': int(mean_color[2])
                },
                'dominant_color': {
                    'r': int(dominant_r),
                    'g': int(dominant_g),
                    'b': int(dominant_b)
                }
            }
        except Exception as e:
            logger.error(f"Error analyzing colors: {e}")
            return {}
    
    def _get_timestamp(self) -> str:
        """Get current timestamp"""
        from datetime import datetime
        return datetime.now().isoformat()


# Global instance
image_analysis_service = ImageAnalysisService()
