#!/usr/bin/env python3
"""
Test script for the standalone face recognition application
Verifies that all required components are available
"""
import os
import sys
import json

def test_requirements():
    """Test if required packages are available"""
    print("🔍 Testing required packages...")
    
    try:
        import cv2
        print(f"✅ OpenCV: {cv2.__version__}")
    except ImportError:
        print("❌ OpenCV not available")
        return False
    
    try:
        import numpy as np
        print(f"✅ NumPy: {np.__version__}")
    except ImportError:
        print("❌ NumPy not available")
        return False
    
    try:
        from PIL import Image
        print(f"✅ Pillow: {Image.__version__}")
    except ImportError:
        print("❌ Pillow not available")
        return False
    
    try:
        import customtkinter as ctk
        print("✅ CustomTkinter available")
    except ImportError:
        print("❌ CustomTkinter not available")
        return False
    
    return True

def test_files():
    """Test if required files exist"""
    print("\n🔍 Testing required files...")
    
    required_files = [
        "face_recognizer.yml",
        "user_data.json",
        "registered_faces/"
    ]
    
    all_exist = True
    for file_path in required_files:
        if os.path.exists(file_path):
            if os.path.isdir(file_path):
                # Count images in directory
                image_count = 0
                for root, dirs, files in os.walk(file_path):
                    for file in files:
                        if file.lower().endswith(('.jpg', '.jpeg', '.png')):
                            image_count += 1
                print(f"✅ {file_path}: {image_count} images found")
            else:
                print(f"✅ {file_path}: exists")
        else:
            print(f"❌ {file_path}: missing")
            all_exist = False
    
    return all_exist

def test_user_data():
    """Test if user data is valid"""
    print("\n🔍 Testing user data...")
    
    try:
        with open("user_data.json", "r") as f:
            data = json.load(f)
        
        print(f"✅ User data loaded: {len(data)} users")
        for user_id, user_info in data.items():
            print(f"   - User {user_id}: {user_info.get('name', 'Unknown')}")
        
        return True
    except Exception as e:
        print(f"❌ Error loading user data: {e}")
        return False

def test_face_recognizer():
    """Test if face recognizer can be loaded"""
    print("\n🔍 Testing face recognizer...")
    
    try:
        import cv2
        recognizer = cv2.face.LBPHFaceRecognizer_create()
        recognizer.read("face_recognizer.yml")
        print("✅ Face recognizer loaded successfully")
        return True
    except Exception as e:
        print(f"❌ Error loading face recognizer: {e}")
        return False

def main():
    """Main test function"""
    print("🚀 Standalone Face Recognition - System Test")
    print("=" * 50)
    
    # Test packages
    if not test_requirements():
        print("\n❌ Package requirements not met. Please install missing packages.")
        print("Run: pip install -r requirements_standalone.txt")
        return False
    
    # Test files
    if not test_files():
        print("\n❌ Required files missing. Please ensure all files are present.")
        return False
    
    # Test user data
    if not test_user_data():
        print("\n❌ User data invalid. Please check user_data.json format.")
        return False
    
    # Test face recognizer
    if not test_face_recognizer():
        print("\n❌ Face recognizer failed to load. Please check face_recognizer.yml.")
        return False
    
    print("\n🎉 All tests passed! The standalone application should work.")
    print("\nTo launch the application:")
    print("1. python launch_standalone.py")
    print("2. Or directly: python standalone_face_recognition_enhanced.py")
    
    return True

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)



