import cv2
import numpy as np
import onnxruntime as ort
import os
import urllib.request

class EmotionDetector:
    """
    Module 4: Lightweight Sentiment Engine (ONNX Powered)
    Includes Auto-Download capability for the AI weights.
    """
    def __init__(self):
        current_dir = os.path.dirname(os.path.abspath(__file__))
        self.model_path = os.path.join(current_dir, "emotion-ferplus-8.onnx")

        # --- THE AUTO-DOWNLOADER ---
        if not os.path.exists(self.model_path):
            self._download_model()

        print("[Aelion Vision] Booting Lightweight Sentiment Engine...")
        self.session = ort.InferenceSession(self.model_path)
        
        self.emotions = ['Neutral', 'Happiness', 'Surprise', 'Sadness', 'Anger', 'Disgust', 'Fear', 'Contempt']

    def _download_model(self):
        """Downloads the 30MB ONNX model tehe very first time the user runs this."""
        print("[Aelion Vision] Initializing AI Brain for the first time...")
        print("[Aelion Vision] Downloading Neural Weights (~30MB). Please wait...")
        url = "http://ai.aelionyxe.top/models/emotion-ferplus-8.onnx"
        
        try:
            urllib.request.urlretrieve(url, self.model_path)
            print("[Aelion Vision] Download Complete! Brain successfully installed.")
        except Exception as e:
            print(f"[!] Critical Error: Failed to download the AI model. Check your internet connection. {e}")

    def analyze(self, frame, face_box):
        try:
            x, y, w, h = face_box
            face_img = frame[y:y+h, x:x+w]
            
            face_gray = cv2.cvtColor(face_img, cv2.COLOR_BGR2GRAY)
            face_resized = cv2.resize(face_gray, (64, 64)).astype(np.float32)
            input_data = face_resized.reshape(1, 1, 64, 64)

            outputs = self.session.run(None, {self.session.get_inputs()[0].name: input_data})
            emotion_idx = np.argmax(outputs[0])
            
            return self.emotions[emotion_idx]
        except Exception as e:
            return "Neutral"