#!/usr/bin/env python3
"""
Test API with correct usage based on actual implementation
"""

import requests
import json
import base64
import os

BASE_URL = "http://localhost:3002"
API_KEY = "muser_243c6725b09f43e29f319a648645b992_1774874668_f224a6d2"


def test_register_face_correct():
    """Test face registration with correct multipart format"""
    print("\n📝 Testing face registration (multipart)...")

    # We need an image file to upload
    test_image = "/tmp/female_faces/female_faces_frame_19778.jpg"

    if not os.path.exists(test_image):
        print(f"❌ Test image not found: {test_image}")
        return False

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

    # Prepare multipart form data
    files = {
        "image": open(test_image, "rb"),
        "name": (None, "Test_Person"),
        "metadata": (
            None,
            json.dumps({"gender": "female", "age": 35, "notes": "Test registration"}),
        ),
    }

    try:
        response = requests.post(
            f"{BASE_URL}/api/v1/face/register", headers=headers, files=files, timeout=30
        )

        print(f"Status: {response.status_code}")
        print(f"Response: {response.text[:200]}")

        if response.status_code == 200:
            print("✅ Face registration successful!")
            return True
        else:
            print("❌ Face registration failed")
            return False

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


def test_recognize_video():
    """Test video face recognition (JSON request)"""
    print("\n🎬 Testing video face recognition...")

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

    payload = {
        "video_uuid": "384b0ff44aaaa1f1",
        "enable_recognition": True,
        "enable_tracking": False,
        "enable_clustering": True,
    }

    try:
        response = requests.post(
            f"{BASE_URL}/api/v1/face/recognize",
            headers=headers,
            json=payload,
            timeout=30,
        )

        print(f"Status: {response.status_code}")

        if response.status_code == 200:
            data = response.json()
            print(f"✅ Video recognition started!")
            print(f"Processing ID: {data.get('processing_id')}")
            print(f"Message: {data.get('message')}")
            return True
        else:
            print(f"Response: {response.text}")
            return False

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


def test_search_faces():
    """Test face search with embedding vector"""
    print("\n🔍 Testing face search...")

    # We need a sample embedding vector
    # For testing, use a dummy vector
    dummy_embedding = [0.1] * 512  # 512-dimensional vector

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

    payload = {"embedding": dummy_embedding, "similarity_threshold": 0.7, "limit": 10}

    try:
        response = requests.post(
            f"{BASE_URL}/api/v1/face/search", headers=headers, json=payload, timeout=30
        )

        print(f"Status: {response.status_code}")

        if response.status_code == 200:
            data = response.json()
            print(f"✅ Face search successful!")
            print(f"Found {len(data.get('matches', []))} matches")
            return True
        else:
            print(f"Response: {response.text}")
            return False

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


def main():
    print("=" * 60)
    print("🧪 Testing API Correct Usage")
    print("=" * 60)

    # Test 1: Face registration (multipart)
    test_register_face_correct()

    # Test 2: Video recognition (JSON)
    test_recognize_video()

    # Test 3: Face search (JSON with embedding)
    test_search_faces()

    print("\n" + "=" * 60)
    print("📋 API Usage Summary:")
    print("=" * 60)
    print("\n1. Face Registration:")
    print("   Method: POST /api/v1/face/register")
    print("   Format: multipart/form-data")
    print("   Fields: image (file), name (text), metadata (JSON)")

    print("\n2. Video Face Recognition:")
    print("   Method: POST /api/v1/face/recognize")
    print("   Format: application/json")
    print("   Body: {video_uuid, enable_recognition, ...}")

    print("\n3. Face Search:")
    print("   Method: POST /api/v1/face/search")
    print("   Format: application/json")
    print("   Body: {embedding: [vector], similarity_threshold, limit}")

    print("\n4. Get Results:")
    print("   Method: GET /api/v1/face/results/{video_uuid}")
    print("   Format: JSON response")

    print("\n5. List Faces:")
    print("   Method: GET /api/v1/face/list")
    print("   Format: JSON response")

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


if __name__ == "__main__":
    main()
