import cv2
import mediapipe as mp
from picamera2 import Picamera2

picam2 = Picamera2()
picam2.configure(picam2.create_preview_configuration(main={"format": "RGB888", "size": (640, 480)}))
picam2.start()

mp_hands = mp.solutions.hands
mp_draw = mp.solutions.drawing_utils
hands = mp_hands.Hands(
     max_num_hands=1,
     model_complexity=0,
     min_detection_confidence=0.6,
    min_tracking_confidence=0.5)

def fingers_up(lm):
    """Return list of 5 bools: [thumb, index, middle, ring, pinky]."""
    fingers = []
    fingers.append(abs(lm[4].x - lm[17].x) > abs(lm[3].x - lm[17].x))
    for tip in [8, 12, 16, 20]:
        fingers.append(lm[tip].y < lm[tip -2].y)
    return fingers

def classify (lm):
    f = fingers_up(lm)
    count = sum(f)
    if count == 0:
        return "FIST"
    if count == 5:
        return "OPEN PALM"
    if f == [False, True, False, False, False]:
        return "POINTING"
    if f == [False, True, True, False, False]:
        return "PEACE"
    if f == [True, False, False, False, False]:
        return "THUMBS UP"
    return f"{count} FINGERS"

print("Running...press q in the window to quit")

while True:
    frame = picam2.capture_array()
    results = hands.process(frame)

    display = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

    gesture = "no_hand"
    if results.multi_hand_landmarks:
        hand_lm = results.multi_hand_landmarks[0]
        mp_draw.draw_landmarks(display, hand_lm,
                               mp_hands.HAND_CONNECTIONS)
        gesture = classify(hand_lm.landmark)

    cv2.putText(display, gesture, (20, 50),
                cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 3)
    cv2.imshow("Gesture Test", display)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

picam2.stop()
cv2.destroyAllWindows()
