#!/usr/bin/env python3
"""
Test face recognition API with correct API key format
"""

import requests
import json
import sys
import os

# API configuration
BASE_URL = "http://localhost:3002"
API_KEY = "muser_243c6725b09f43e29f319a648645b992_1774874668_f224a6d2"  # Replace with your actual key
VIDEO_UUID = "384b0ff44aaaa1f1"  # Old_Time_Movie_Show_-_Charade_1963.HD.mov


def test_api_key():
    """Test API key validation"""
    print("🔑 Testing API key validation...")

    headers = {"X-API-Key": API_KEY}

    try:
        response = requests.get(f"{BASE_URL}/api/v1/health", headers=headers)
        print(f"Status: {response.status_code}")
        print(f"Response: {response.text}")

        if response.status_code == 200:
            print("✅ API key validation successful!")
            return True
        else:
            print(f"❌ API key validation failed: {response.status_code}")
            return False

    except Exception as e:
        print(f"❌ Error: {e}")
        return False


def test_face_list():
    """Test face list endpoint"""
    print("\n📋 Testing face list endpoint...")

    headers = {"X-API-Key": API_KEY}

    try:
        response = requests.get(f"{BASE_URL}/api/v1/face/list", headers=headers)
        print(f"Status: {response.status_code}")

        if response.status_code == 200:
            data = response.json()
            print(f"✅ Success! Found {len(data.get('faces', []))} registered faces")
            print(f"Response: {json.dumps(data, indent=2)}")
            return True
        else:
            print(f"Response: {response.text}")
            return False

    except Exception as e:
        print(f"❌ Error: {e}")
        return False


def test_face_results():
    """Test face analysis results endpoint"""
    print(f"\n🎬 Testing face results for video {VIDEO_UUID}...")

    headers = {"X-API-Key": API_KEY}

    try:
        response = requests.get(
            f"{BASE_URL}/api/v1/face/results/{VIDEO_UUID}", headers=headers
        )
        print(f"Status: {response.status_code}")

        if response.status_code == 200:
            data = response.json()
            print(f"✅ Success! Found {data.get('total_faces', 0)} faces in video")
            print(f"Video: {data.get('video_uuid')}")
            print(f"Total faces: {data.get('total_faces')}")
            print(f"Analysis time: {data.get('analysis_time_seconds')}s")
            return True
        else:
            print(f"Response: {response.text}")
            return False

    except Exception as e:
        print(f"❌ Error: {e}")
        return False


def test_face_register():
    """Test face registration endpoint"""
    print("\n👤 Testing face registration...")

    headers = {"X-API-Key": API_KEY, "Content-Type": "application/json"}

    # Register one of the female faces from frame 19778
    payload = {
        "video_uuid": VIDEO_UUID,
        "frame_number": 19778,
        "face_index": 0,  # First face in the frame
        "person_name": "Audrey_Hepburn",  # Assuming this is Audrey Hepburn
        "metadata": {
            "gender": "female",
            "age": 34,
            "confidence": 0.95,
            "notes": "Main actress in Charade (1963)",
        },
    }

    try:
        response = requests.post(
            f"{BASE_URL}/api/v1/face/register", headers=headers, json=payload
        )
        print(f"Status: {response.status_code}")

        if response.status_code == 200:
            data = response.json()
            print(f"✅ Success! Face registered with ID: {data.get('face_id')}")
            print(f"Person: {data.get('person_name')}")
            print(f"Embedding vector length: {len(data.get('embedding', []))}")
            return True
        else:
            print(f"Response: {response.text}")
            return False

    except Exception as e:
        print(f"❌ Error: {e}")
        return False


def test_face_recognize():
    """Test face recognition endpoint"""
    print("\n🔍 Testing face recognition...")

    # First, let's get a sample face image from our analysis
    sample_image_path = "/tmp/female_faces/female_faces_frame_19778.jpg"

    if not os.path.exists(sample_image_path):
        print(f"⚠️ Sample image not found: {sample_image_path}")
        print("Skipping recognition test...")
        return False

    headers = {"X-API-Key": API_KEY}

    files = {"image": open(sample_image_path, "rb")}

    try:
        response = requests.post(
            f"{BASE_URL}/api/v1/face/recognize", headers=headers, files=files
        )
        print(f"Status: {response.status_code}")

        if response.status_code == 200:
            data = response.json()
            print(f"✅ Success! Recognition results:")
            print(f"Total faces detected: {data.get('total_faces', 0)}")

            matches = data.get("matches", [])
            if matches:
                for i, match in enumerate(matches):
                    print(f"\nMatch {i + 1}:")
                    print(f"  Person: {match.get('person_name', 'Unknown')}")
                    print(f"  Confidence: {match.get('confidence', 0):.3f}")
                    print(f"  Distance: {match.get('distance', 0):.3f}")
            else:
                print("No matches found (face not registered yet)")

            return True
        else:
            print(f"Response: {response.text}")
            return False

    except Exception as e:
        print(f"❌ Error: {e}")
        return False
    finally:
        if "files" in locals():
            files["image"].close()


def main():
    print("=" * 60)
    print("🧪 Face Recognition API Test with Correct Key Format")
    print("=" * 60)

    # Test 1: API key validation
    if not test_api_key():
        print("\n❌ API key test failed. Exiting.")
        return

    # Test 2: Face list
    if not test_face_list():
        print("\n⚠️ Face list test failed, but continuing...")

    # Test 3: Face results
    if not test_face_results():
        print("\n⚠️ Face results test failed, but continuing...")

    # Test 4: Face registration (learning)
    if not test_face_register():
        print("\n⚠️ Face registration test failed, but continuing...")

    # Test 5: Face recognition
    if not test_face_recognize():
        print("\n⚠️ Face recognition test failed.")

    print("\n" + "=" * 60)
    print("✅ All tests completed!")
    print("=" * 60)


if __name__ == "__main__":
    main()
