#!/usr/bin/env python3
"""
Webcam face presence detector using OpenCV haar cascades.
Exit codes: 0 = face detected, 1 = no face, 2 = camera error
Usage: presence_detect.py [camera_id]
"""
import sys
import cv2

FRAMES_TO_CHECK = 6
FACES_NEEDED = 2        # require face in at least N frames to count as present
SCALE_FACTOR = 1.1
MIN_NEIGHBORS = 4


def detect(camera_id: int) -> int:
    cap = cv2.VideoCapture(camera_id)
    if not cap.isOpened():
        return 2

    cascade = cv2.CascadeClassifier(
        cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
    )
    detected = 0
    try:
        for _ in range(FRAMES_TO_CHECK):
            ok, frame = cap.read()
            if not ok:
                continue
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            faces = cascade.detectMultiScale(gray, SCALE_FACTOR, MIN_NEIGHBORS)
            if len(faces) > 0:
                detected += 1
    finally:
        cap.release()

    return 0 if detected >= FACES_NEEDED else 1


if __name__ == "__main__":
    camera_id = int(sys.argv[1]) if len(sys.argv) > 1 else 0
    sys.exit(detect(camera_id))
