#!/usr/bin/env python3
"""
Test if RetinaFace provides both eyes for profile faces or if one eye is missing
"""

import sys
import os

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

try:
    from src.utils.pose_detection import PoseDetector, RETINAFACE_AVAILABLE
    from pathlib import Path
    
    if not RETINAFACE_AVAILABLE:
        print("❌ RetinaFace not available")
        exit(1)
    
    detector = PoseDetector()
    
    # Find test images
    test_image_paths = ["demo_photos", "data/uploads"]
    test_image = None
    
    for path in test_image_paths:
        if os.path.exists(path):
            for ext in ['.jpg', '.jpeg', '.png']:
                for img_file in Path(path).glob(f'*{ext}'):
                    test_image = str(img_file)
                    break
            if test_image:
                break
    
    if not test_image:
        print("❌ No test image found")
        exit(1)
    
    print(f"Testing with: {test_image}\n")
    print("=" * 80)
    print("EYE VISIBILITY ANALYSIS")
    print("=" * 80)
    
    faces = detector.detect_faces_with_landmarks(test_image)
    
    if not faces:
        print("❌ No faces detected")
        exit(1)
    
    print(f"Found {len(faces)} face(s)\n")
    
    for face_key, face_data in faces.items():
        landmarks = face_data.get('landmarks', {})
        print(f"{face_key}:")
        print(f"  Landmarks available: {list(landmarks.keys())}")
        
        left_eye = landmarks.get('left_eye')
        right_eye = landmarks.get('right_eye')
        nose = landmarks.get('nose')
        
        print(f"  Left eye: {left_eye}")
        print(f"  Right eye: {right_eye}")
        print(f"  Nose: {nose}")
        
        # Check if both eyes are present
        both_eyes_present = left_eye is not None and right_eye is not None
        only_left_eye = left_eye is not None and right_eye is None
        only_right_eye = left_eye is None and right_eye is not None
        no_eyes = left_eye is None and right_eye is None
        
        print(f"\n  Eye visibility:")
        print(f"    Both eyes present: {both_eyes_present}")
        print(f"    Only left eye: {only_left_eye}")
        print(f"    Only right eye: {only_right_eye}")
        print(f"    No eyes: {no_eyes}")
        
        # Calculate yaw if possible
        yaw = detector.calculate_yaw_from_landmarks(landmarks)
        print(f"  Yaw angle: {yaw:.2f}°" if yaw is not None else "  Yaw angle: None (requires both eyes)")
        
        # Calculate face width if both eyes present
        if both_eyes_present:
            face_width = abs(right_eye[0] - left_eye[0])
            print(f"  Face width (eye distance): {face_width:.2f} pixels")
            
            # If face width is very small, it might be a profile view
            if face_width < 20:
                print(f"  ⚠️  Very small face width - likely extreme profile view")
        
        # Classify pose
        pitch = detector.calculate_pitch_from_landmarks(landmarks)
        roll = detector.calculate_roll_from_landmarks(landmarks)
        pose_mode = detector.classify_pose_mode(yaw, pitch, roll)
        
        print(f"  Pose mode: {pose_mode}")
        print()
    
    print("\n" + "=" * 80)
    print("CONCLUSION")
    print("=" * 80)
    print("""
If RetinaFace provides both eyes even for profile faces:
  - We can use eye distance (face width) as an indicator
  - Small face width (< 20-30 pixels) suggests extreme profile
  - But we can't directly use 'missing eye' as a signal

If RetinaFace sometimes only provides one eye for profile faces:
  - We can check if left_eye or right_eye is None
  - If only one eye is present, it's likely a profile view
  - This would be a strong indicator for profile detection
    """)
    
except ImportError as e:
    print(f"❌ Import error: {e}")
    print("Make sure you're in the project directory and dependencies are installed")

