#!/usr/bin/env python3
"""
OpenCV Face Detection Demo
A working alternative to the face_recognition library examples
"""

import cv2
import numpy as np
from PIL import Image
import os

def detect_faces_in_image(image_path):
    """Detect faces in a static image"""
    print(f"Analyzing image: {image_path}")
    
    # Load the image
    image = cv2.imread(image_path)
    if image is None:
        print(f"Could not load image: {image_path}")
        return
    
    # Convert to grayscale for face detection
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # Load face detection classifier
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
    
    # Detect faces
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    
    print(f"I found {len(faces)} face(s) in this photograph.")
    
    # Draw rectangles around faces and show results
    for i, (x, y, w, h) in enumerate(faces):
        print(f"Face {i+1} is located at: Top: {y}, Left: {x}, Bottom: {y+h}, Right: {x+w}")
        
        # Draw rectangle around face
        cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
        
        # Add face number label
        cv2.putText(image, f'Face {i+1}', (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
    
    # Display the result
    cv2.imshow('Face Detection Results', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
    return faces

def webcam_face_detection():
    """Real-time face detection from webcam"""
    print("Starting webcam face detection...")
    print("Press 'q' to quit")
    
    # Initialize webcam
    cap = cv2.VideoCapture(0)
    
    # Load face detection classifier
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
    
    while True:
        # Capture frame-by-frame
        ret, frame = cap.read()
        if not ret:
            break
        
        # Convert to grayscale for face detection
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        
        # Detect faces
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        
        # Draw rectangles around faces
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
            cv2.putText(frame, 'Face Detected', (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
        
        # Display face count
        cv2.putText(frame, f'Faces: {len(faces)}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
        
        # Display the resulting frame
        cv2.imshow('Webcam Face Detection', frame)
        
        # Break the loop when 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    # Release everything
    cap.release()
    cv2.destroyAllWindows()

def main():
    """Main demo function"""
    print("🔍 OpenCV Face Detection Demo")
    print("=" * 40)
    
    while True:
        print("\nChoose an option:")
        print("1. Detect faces in Obama image")
        print("2. Detect faces in Biden image") 
        print("3. Detect faces in two_people image")
        print("4. Start webcam face detection")
        print("5. Exit")
        
        choice = input("\nEnter your choice (1-5): ").strip()
        
        if choice == '1':
            detect_faces_in_image('obama.jpg')
        elif choice == '2':
            detect_faces_in_image('biden.jpg')
        elif choice == '3':
            detect_faces_in_image('two_people.jpg')
        elif choice == '4':
            webcam_face_detection()
        elif choice == '5':
            print("Goodbye! 👋")
            break
        else:
            print("Invalid choice. Please try again.")

if __name__ == "__main__":
    main()