import cv2
import face_recognition
import os
import numpy as np

class SecurityVault:
    """
    Module 5: The Identity Vault
    Fast, real-time comparison using 128-D Vector Embeddings.
    """
    def __init__(self, db_path="aelion_db"):
        self.db_path = db_path
        self.known_encodings = []
        self.known_names = []
        self.load_vault()

    def load_vault(self):
        """Loads all faces from your folder into RAM for instant comparison."""
        if not os.path.exists(self.db_path): os.makedirs(self.db_path)
        
        for file in os.listdir(self.db_path):
            img = face_recognition.load_image_file(f"{self.db_path}/{file}")
            encoding = face_recognition.face_encodings(img)[0]
            self.known_encodings.append(encoding)
            self.known_names.append(os.path.splitext(file)[0])
        print(f"[Aelion Vision] Vault loaded: {len(self.known_names)} identities ready.")

    def match(self, frame, face_location):
        """Compares a live face against the vault."""
        encoding = face_recognition.face_encodings(frame, [face_location])[0]
        matches = face_recognition.compare_faces(self.known_encodings, encoding, tolerance=0.5)
        
        if True in matches:
            first_match_index = matches.index(True)
            return self.known_names[first_match_index]
        return "Unknown"