#!/usr/bin/env python3
"""
Test Recognition Script
This script tests if the face recognition model is working correctly.
"""

import cv2
import numpy as np
import os

def test_model():
    """Test the trained model"""
    print("🧪 Testing Face Recognition Model...")
    
    # Check if model exists
    model_file = "face_recognizer.yml"
    if not os.path.exists(model_file):
        print(f"❌ Model file {model_file} not found!")
        return False
    
    print(f"✅ Model file found: {model_file}")
    
    try:
        # Create recognizer and load model
        recognizer = cv2.face.LBPHFaceRecognizer_create()
        recognizer.read(model_file)
        print("✅ Model loaded successfully")
        
        # Test with a sample image from User 332 (Alejo)
        test_image_path = "registered_faces/332/front/0.jpg"
        if not os.path.exists(test_image_path):
            print(f"❌ Test image not found: {test_image_path}")
            return False
        
        print(f"📸 Testing with image: {test_image_path}")
        
        # Load and preprocess the test image
        img = cv2.imread(test_image_path, cv2.IMREAD_GRAYSCALE)
        if img is None:
            print(f"❌ Failed to load test image")
            return False
        
        print(f"✅ Test image loaded: {img.shape}")
        
        # Preprocess the image (same as training)
        from livestream import preprocess_face
        processed_img = preprocess_face(img)
        print(f"✅ Image preprocessed: {processed_img.shape}")
        
        # Try to predict
        user_id, confidence = recognizer.predict(processed_img)
        print(f"🎯 Prediction result:")
        print(f"   User ID: {user_id}")
        print(f"   Confidence: {confidence}")
        
        # Check if prediction makes sense
        if user_id == 332:
            print(f"✅ Correctly predicted User 332 (Alejo)")
        else:
            print(f"❌ Predicted wrong user: {user_id} (expected 332)")
        
        if confidence < 120:
            print(f"✅ Confidence below threshold (good recognition)")
        else:
            print(f"❌ Confidence above threshold (poor recognition)")
        
        return True
        
    except Exception as e:
        print(f"❌ Error testing model: {e}")
        return False

def test_all_users():
    """Test recognition for all users"""
    print("\n🔍 Testing Recognition for All Users...")
    
    try:
        recognizer = cv2.face.LBPHFaceRecognizer_create()
        recognizer.read("face_recognizer.yml")
        
        # Test each user
        for user_id in ["332", "145852", "1383"]:
            user_folder = os.path.join("registered_faces", user_id)
            if os.path.exists(user_folder):
                # Find a test image
                test_image = None
                for angle in ["front", "left", "right", "up", "down"]:
                    angle_path = os.path.join(user_folder, angle)
                    if os.path.exists(angle_path):
                        images = [f for f in os.listdir(angle_path) if f.endswith('.jpg')]
                        if images:
                            test_image = os.path.join(angle_path, images[0])
                            break
                
                if test_image:
                    print(f"\n📸 Testing User {user_id} with {test_image}...")
                    
                    img = cv2.imread(test_image, cv2.IMREAD_GRAYSCALE)
                    if img is not None:
                        from livestream import preprocess_face
                        processed_img = preprocess_face(img)
                        
                        predicted_id, confidence = recognizer.predict(processed_img)
                        
                        print(f"  Expected: {user_id}")
                        print(f"  Predicted: {predicted_id}")
                        print(f"  Confidence: {confidence:.2f}")
                        
                        if str(predicted_id) == user_id:
                            print(f"  ✅ Correct recognition!")
                        else:
                            print(f"  ❌ Wrong recognition!")
                        
                        if confidence < 120:
                            print(f"  ✅ Good confidence")
                        else:
                            print(f"  ❌ Poor confidence")
                    else:
                        print(f"  ❌ Failed to load image")
                else:
                    print(f"❌ No test image found for User {user_id}")
    
    except Exception as e:
        print(f"❌ Error testing all users: {e}")

def main():
    """Main test function"""
    print("Face Recognition Test")
    print("=" * 30)
    
    # Test basic model functionality
    if test_model():
        print("\n✅ Basic model test passed!")
        
        # Test all users
        test_all_users()
    else:
        print("\n❌ Basic model test failed!")

if __name__ == "__main__":
    main()



