#!/usr/bin/env python3
"""
Register sample faces to test the face recognition system
"""

import requests
import json
import base64
import os

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


def register_face(frame_number, face_index, person_name, gender, age, notes=""):
    """Register a face from the analyzed video"""
    print(f"\n👤 Registering {person_name}...")

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

    payload = {
        "video_uuid": VIDEO_UUID,
        "frame_number": frame_number,
        "face_index": face_index,
        "person_name": person_name,
        "metadata": {
            "gender": gender,
            "age": age,
            "confidence": 0.95,
            "notes": notes,
            "source_video": "Charade (1963)",
            "timestamp_seconds": frame_number / 30.0,  # Assuming 30fps
        },
    }

    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 ID: {data.get('face_id')}")
            print(f"   Person: {data.get('person_name')}")
            print(f"   Embedding: {len(data.get('embedding', []))} dimensions")
            return True
        else:
            print(f"❌ Failed: {response.text}")
            return False

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


def test_recognition():
    """Test face recognition with a sample image"""
    print("\n🔍 Testing face recognition...")

    # Use the female faces frame we extracted earlier
    sample_image = "/tmp/female_faces/female_faces_frame_19778.jpg"

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

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

    files = {"image": open(sample_image, "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! Total faces detected: {data.get('total_faces', 0)}")

            matches = data.get("matches", [])
            if matches:
                print(f"\nFound {len(matches)} matches:")
                for i, match in enumerate(matches):
                    print(
                        f"  {i + 1}. {match.get('person_name', 'Unknown')} "
                        f"(confidence: {match.get('confidence', 0):.3f})"
                    )
            else:
                print("No matches found (try registering faces first)")

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

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


def list_faces():
    """List all registered faces"""
    print("\n📋 Listing registered faces...")

    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()
            faces = data.get("faces", [])
            print(f"✅ Found {len(faces)} registered faces:")

            for face in faces:
                print(f"  • {face.get('name')} (ID: {face.get('face_id')})")

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

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


def main():
    print("=" * 60)
    print("👥 Face Registration Test")
    print("=" * 60)

    # Register some sample faces from the video
    # Based on our analysis, frame 19778 has 3 female faces

    print(f"\n📹 Source video: {VIDEO_UUID}")
    print("   Frame 19778 (5:29) has 3 female faces")

    # Register faces (assuming these are the actors in Charade)
    faces_to_register = [
        {
            "frame": 19778,
            "index": 0,
            "name": "Audrey_Hepburn",
            "gender": "female",
            "age": 34,
            "notes": "Main actress in Charade (1963)",
        },
        {
            "frame": 19778,
            "index": 1,
            "name": "Cary_Grant",
            "gender": "male",
            "age": 59,
            "notes": "Main actor in Charade (1963)",
        },
        {
            "frame": 17980,  # Another frame with 2 females
            "index": 0,
            "name": "Supporting_Actress_1",
            "gender": "female",
            "age": 28,
            "notes": "Supporting actress",
        },
    ]

    success_count = 0
    for face in faces_to_register:
        if register_face(
            face["frame"],
            face["index"],
            face["name"],
            face["gender"],
            face["age"],
            face["notes"],
        ):
            success_count += 1

    print(f"\n📊 Registered {success_count}/{len(faces_to_register)} faces")

    # List registered faces
    list_faces()

    # Test recognition
    test_recognition()

    print("\n" + "=" * 60)
    print("✅ Face registration test completed!")
    print("=" * 60)


if __name__ == "__main__":
    main()
