#!/usr/bin/env python3
"""
Test Live Recognition Script
This script tests the live recognition endpoint to see if it's working.
"""

import requests
import cv2
import numpy as np
import base64
import json

def test_recognition_endpoint():
    """Test the recognition endpoint with a real image"""
    print("🧪 Testing Live Recognition Endpoint...")
    
    # Test image path (use one of your registered images)
    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"📸 Using test image: {test_image_path}")
    
    try:
        # Read and encode the image
        with open(test_image_path, "rb") as image_file:
            image_data = base64.b64encode(image_file.read()).decode('utf-8')
        
        print(f"✅ Image encoded successfully")
        
        # Prepare the request
        url = "http://localhost:5001/recognize"
        payload = {
            "image": image_data
        }
        
        print(f"🌐 Sending request to: {url}")
        
        # Send the request
        response = requests.post(url, json=payload)
        
        print(f"📡 Response status: {response.status_code}")
        print(f"📡 Response headers: {dict(response.headers)}")
        
        if response.status_code == 200:
            result = response.json()
            print(f"✅ Recognition successful!")
            print(f"📊 Response: {json.dumps(result, indent=2)}")
            
            # Check if user was recognized
            if "user_id" in result:
                print(f"🎯 Recognized User ID: {result['user_id']}")
                if "user_name" in result:
                    print(f"👤 User Name: {result['user_name']}")
                if "confidence" in result:
                    print(f"📈 Confidence: {result['confidence']}")
            else:
                print(f"❌ No user recognized in response")
                
        else:
            print(f"❌ Recognition failed!")
            print(f"📄 Response text: {response.text}")
            
        return response.status_code == 200
        
    except Exception as e:
        print(f"❌ Error testing recognition: {e}")
        return False

def test_server_status():
    """Test if the server is responding"""
    print("🔍 Testing Server Status...")
    
    try:
        # Test basic server response
        response = requests.get("http://localhost:5001/", timeout=5)
        print(f"📡 Server response: {response.status_code}")
        return True
    except requests.exceptions.ConnectionError:
        print("❌ Cannot connect to server")
        return False
    except Exception as e:
        print(f"❌ Server test error: {e}")
        return False

def main():
    """Main test function"""
    print("Live Recognition Test")
    print("=" * 30)
    
    # Test server status first
    if not test_server_status():
        print("\n❌ Server is not responding properly!")
        return
    
    print("\n✅ Server is responding")
    
    # Test recognition endpoint
    if test_recognition_endpoint():
        print("\n✅ Recognition endpoint is working!")
    else:
        print("\n❌ Recognition endpoint has issues!")

if __name__ == "__main__":
    import os
    main()



