import cv2
import time
import os
import tkinter as tk
from tkinter import Label
from PIL import Image, ImageTk
from datetime import datetime
from threading import Thread

# Popup window with static image
def show_alert_popup(image_path):
    def create_popup():
        popup = tk.Tk()
        popup.title("Onlooker+ Alert")
        popup.configure(bg='#1a1a1a')
        popup.attributes('-topmost', True)

        # Position top-right
        popup.geometry('320x400+{}+50'.format(popup.winfo_screenwidth() - 340))

        # Title
        title = Label(popup, text="ONLOOKER DETECTED!", font=('Segoe UI', 14, 'bold'),
                     fg='#ef4444', bg='#1a1a1a')
        title.pack(pady=(15, 5))

        # Subtitle
        subtitle = Label(popup, text="Someone is looking at your screen",
                        font=('Segoe UI', 10), fg='#999', bg='#1a1a1a')
        subtitle.pack(pady=(0, 10))

        # Load and show image
        img = Image.open(image_path)
        img = img.resize((280, 280))
        photo = ImageTk.PhotoImage(img)
        img_label = Label(popup, image=photo, bg='#1a1a1a',
                         highlightthickness=3, highlightbackground='#6366f1')
        img_label.image = photo
        img_label.pack(pady=10)

        # Close button
        close_btn = tk.Button(popup, text="Dismiss", command=popup.destroy,
                             font=('Segoe UI', 10), bg='#6366f1', fg='white',
                             relief='flat', padx=20, pady=5, cursor='hand2')
        close_btn.pack(pady=10)

        # Auto-close after 5 seconds
        popup.after(5000, popup.destroy)
        popup.mainloop()

    Thread(target=create_popup, daemon=True).start()

# Load face detector
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

last_alert = 0
COOLDOWN = 5
face_detected_frames = 0
FRAMES_TO_CONFIRM = 5
last_faces = []

print("Onlooker+ running... Press Q to quit")

while True:
    ret, frame = cap.read()
    if not ret:
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(
        gray, scaleFactor=1.1, minNeighbors=8,
        minSize=(80, 80), flags=cv2.CASCADE_SCALE_IMAGE
    )

    if len(faces) > 0:
        last_faces = faces
        face_detected_frames += 1
    else:
        face_detected_frames = max(0, face_detected_frames - 1)
        if face_detected_frames > 0:
            faces = last_faces

    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (241, 102, 99), 3)
        cv2.putText(frame, "DETECTED", (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)

        if face_detected_frames >= FRAMES_TO_CONFIRM and time.time() - last_alert > COOLDOWN:
            # Save cropped face to catches folder
            face_img = frame[y:y+h, x:x+w]
            catches_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "catches")
            os.makedirs(catches_dir, exist_ok=True)
            face_file = f"face_{datetime.now().strftime('%H%M%S')}.jpg"
            face_path = os.path.join(catches_dir, face_file)
            cv2.imwrite(face_path, face_img)

            print(f"[!] ONLOOKER DETECTED! Saved: {face_file}")

            # Show popup with static image
            show_alert_popup(face_path)

            last_alert = time.time()

    status = "FACE DETECTED" if face_detected_frames >= FRAMES_TO_CONFIRM else "Monitoring..."
    color = (0, 0, 255) if face_detected_frames >= FRAMES_TO_CONFIRM else (0, 255, 0)
    cv2.putText(frame, f"Onlooker+ | {status}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2)
    cv2.imshow('Onlooker+', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
print("Onlooker+ stopped")
