import cv2
import mediapipe as mp
import pyautogui
import time


class AutoReelScroller:
    def __init__(self, scroll_up_hand="Right", scroll_down_hand="Left", sensitivity=50):
        self.scroll_up_hand = scroll_up_hand
        self.scroll_down_hand = scroll_down_hand
        self.sensitivity = sensitivity
        self.mp_hands = mp.solutions.hands
        self.hands = self.mp_hands.Hands(
            min_detection_confidence=0.7, min_tracking_confidence=0.7
        )
        self.prev_y_right = None
        self.prev_y_left = None

    def start_scrolling(self):
        print("Starting Auto Reel Scroller AI...")
        cap = cv2.VideoCapture(0)

        while cap.isOpened():
            ret, frame = cap.read()
            if not ret:
                break

            frame = cv2.flip(frame, 1)  # Mirror effect
            h, w, _ = frame.shape
            rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            results = self.hands.process(rgb_frame)

            if results.multi_hand_landmarks and results.multi_handedness:
                for idx, hand_landmarks in enumerate(results.multi_hand_landmarks):
                    hand_label = results.multi_handedness[idx].classification[0].label
                    y = hand_landmarks.landmark[
                        self.mp_hands.HandLandmark.INDEX_FINGER_TIP
                    ].y * h

                    if hand_label == self.scroll_up_hand and self.prev_y_right is not None:
                        if self.prev_y_right - y > self.sensitivity:
                            pyautogui.scroll(-500)  # Scroll up
                            time.sleep(1)
                        self.prev_y_right = y

                    elif hand_label == self.scroll_down_hand and self.prev_y_left is not None:
                        if y - self.prev_y_left > self.sensitivity:
                            pyautogui.scroll(500)  # Scroll down
                            time.sleep(1)
                        self.prev_y_left = y

            cv2.imshow("Reel Scroller AI", frame)
            if cv2.waitKey(1) & 0xFF == ord("q"):
                break

        cap.release()
        cv2.destroyAllWindows()


def main():
    scroller = AutoReelScroller()
    scroller.start_scrolling()


if __name__ == "__main__":
    main()
