#!/usr/bin/env python3
"""
Add Reference Face Script
Adds a reference face encoding to the database
"""

import sys
import os
import resource
import time

# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from modules.unified_database import UnifiedDatabase
from modules.face_recognition_module import FaceRecognitionModule

# Limit CPU usage at Python level to prevent system freeze
try:
    os.nice(19)  # Lowest CPU priority
except OSError:
    pass

try:
    # Limit CPU time to 120 seconds max (face recognition can be slow)
    resource.setrlimit(resource.RLIMIT_CPU, (120, 120))
except (OSError, ValueError):
    pass

# Small delay to reduce CPU spike
time.sleep(0.2)


def main():
    if len(sys.argv) < 3:
        print("Usage: python3 add_reference_face.py <person_name> <image_path>")
        print("Example: python3 add_reference_face.py 'Eva Longoria' /path/to/reference_image.jpg")
        sys.exit(1)

    person_name = sys.argv[1]
    image_path = sys.argv[2]

    if not os.path.exists(image_path):
        print(f"Error: Image not found: {image_path}")
        sys.exit(1)

    print(f"Adding reference face for '{person_name}' from {image_path}")

    # Initialize database
    db = UnifiedDatabase()

    # Initialize face recognition module
    face_module = FaceRecognitionModule(unified_db=db)

    # Add reference face
    success = face_module.add_reference_face(person_name, image_path)

    if success:
        print(f"✓ Successfully added reference face for '{person_name}'")
        print(f"\nCurrent reference faces:")

        refs = face_module.get_reference_faces()
        for ref in refs:
            print(f"  - {ref['person_name']} (ID: {ref['id']}, added: {ref['created_at']})")
    else:
        print(f"✗ Failed to add reference face")
        sys.exit(1)


if __name__ == "__main__":
    main()
