"""
CLIP Zero-Shot Classification Model for Property Verification

CLIP (Contrastive Language-Image Pre-training) by OpenAI:
1. Encodes both images and text into the same embedding space
2. Compares image embeddings with text prompt embeddings
3. Calculates similarity scores to determine which text best describes the image
4. Works with any text prompt without needing task-specific training (zero-shot)

This is perfect for classifying images as "house/property" vs "not a house" without
needing a custom-trained classifier.
"""

from transformers import CLIPProcessor, CLIPModel
from PIL import Image
import torch
from typing import Dict, List, 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 CLIP_MODEL, CLIP_PROMPTS, CLIP_THRESHOLD

logger = logging.getLogger(__name__)


class CLIPClassifier:
    """
    CLIP-based zero-shot classifier for property image verification.
    """
    
    def __init__(self):
        """
        Initialize the CLIP model and processor.
        The model will be downloaded automatically on first run.
        """
        try:
            logger.info(f"Loading CLIP model: {CLIP_MODEL}")
            
            # Load CLIP model and processor
            self.model = CLIPModel.from_pretrained(CLIP_MODEL)
            self.processor = CLIPProcessor.from_pretrained(CLIP_MODEL)
            
            # Move model to GPU if available
            self.device = "cuda" if torch.cuda.is_available() else "cpu"
            self.model.to(self.device)
            
            self.prompts = CLIP_PROMPTS
            self.threshold = CLIP_THRESHOLD
            
            logger.info(f"CLIP model loaded successfully on {self.device}")
            
        except Exception as e:
            logger.error(f"Failed to load CLIP model: {e}")
            raise
    
    def classify_image(self, image_path: str) -> Tuple[bool, Dict[str, float], str]:
        """
        Classify an image using zero-shot CLIP classification.
        
        Args:
            image_path: Path to the image file
            
        Returns:
            Tuple containing:
            - is_valid: Boolean indicating if image is a valid property image
            - probabilities: Dictionary mapping prompts to their probabilities
            - prediction: The most likely prompt/category
        """
        try:
            # Load and preprocess image
            image = Image.open(image_path).convert("RGB")
            
            # Prepare inputs for CLIP
            # The processor handles tokenization of text and image preprocessing
            inputs = self.processor(
                text=self.prompts,
                images=image,
                return_tensors="pt",
                padding=True
            )
            
            # Move inputs to the same device as model
            inputs = {k: v.to(self.device) for k, v in inputs.items()}
            
            # Get model predictions
            with torch.no_grad():
                outputs = self.model(**inputs)
                
                # Calculate similarity scores between image and text prompts
                logits_per_image = outputs.logits_per_image
                
                # Convert to probabilities using softmax
                probs = logits_per_image.softmax(dim=1)
            
            # Convert to CPU and numpy for easier handling
            probs = probs.cpu().numpy()[0]
            
            # Create probability dictionary
            probabilities = {
                prompt: float(prob) 
                for prompt, prob in zip(self.prompts, probs)
            }
            
            # Find the most likely category
            max_idx = probs.argmax()
            prediction = self.prompts[max_idx]
            max_prob = float(probs[max_idx])
            
            # Determine if image is valid
            # Valid if "house" or "interior room" has probability > threshold
            # AND "not a house" has lower probability
            house_prob = probabilities.get("a photo of a house", 0)
            interior_prob = probabilities.get("an interior room", 0)
            not_house_prob = probabilities.get("not a house", 0)
            
            property_prob = max(house_prob, interior_prob)
            is_valid = property_prob > self.threshold and property_prob > not_house_prob
            
            logger.info(f"CLIP Classification - Valid: {is_valid}, Prediction: {prediction} ({max_prob:.3f})")
            logger.info(f"Probabilities: {probabilities}")
            
            return is_valid, probabilities, prediction
            
        except Exception as e:
            logger.error(f"Error during CLIP classification: {e}")
            return False, {}, "error"
    
    def get_model_info(self) -> Dict:
        """
        Get information about the loaded CLIP model.
        """
        return {
            "model_name": CLIP_MODEL,
            "device": self.device,
            "prompts": self.prompts,
            "threshold": self.threshold
        }