#!/usr/bin/env python3
"""
Debug Predict Method
This script tests the predict method directly to see what's causing the error.
"""
import cv2
import numpy as np
import os
from livestream import preprocess_face

def test_predict():
    print("Testing predict method directly...")
    
    # Load the model
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    model_file = "face_recognizer.yml"
    
    if not os.path.exists(model_file):
        print(f"❌ Model file not found: {model_file}")
        return
    
    print(f"✅ Model file found: {model_file}")
    recognizer.read(model_file)
    print("✅ Model loaded successfully")
    
    # Load a test image
    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
    
    print(f"✅ Test image found: {test_image_path}")
    
    # Load and preprocess the image (same as working test script)
    img = cv2.imread(test_image_path, cv2.IMREAD_GRAYSCALE)
    if img is None:
        print("❌ Failed to load image")
        return
    
    print(f"✅ Image loaded: {img.shape}")
    
    # Preprocess the whole image (same as working test script)
    face_img = preprocess_face(img)
    print(f"✅ Image preprocessed: {face_img.shape}")
    
    # Test predict method
    try:
        print("🔍 Calling predict method...")
        result = recognizer.predict(face_img)
        print(f"✅ Predict result: {result}")
        print(f"Result type: {type(result)}")
        print(f"Result length: {len(result) if hasattr(result, '__len__') else 'No length'}")
        
        # Try to unpack
        if isinstance(result, tuple):
            print("Result is tuple")
            if len(result) == 2:
                user_id, confidence = result
                print(f"Successfully unpacked: user_id={user_id}, confidence={confidence}")
            else:
                print(f"Tuple has {len(result)} elements, expected 2")
        elif isinstance(result, (list, np.ndarray)):
            print("Result is list/array")
            if len(result) >= 2:
                user_id, confidence = result[0], result[1]
                print(f"Successfully unpacked: user_id={user_id}, confidence={confidence}")
            else:
                print(f"List/array has {len(result)} elements, expected at least 2")
        else:
            print("Result is neither tuple nor list/array")
            user_id = result
            confidence = 0.0
            print(f"Using single value: user_id={user_id}, confidence={confidence}")
            
    except Exception as e:
        print(f"❌ Error in predict: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    test_predict()
