import cv2
import time
import os
import smtplib
from email.message import EmailMessage
import glob

# --- Configuration ---
# Camera settings
CAMERA_INDEX = 0 # Usually 0 for built-in, 1 or higher for external USB
NUM_IMAGES = 5
INTERVAL_SECONDS = 21.5
IMAGE_DIR = "target_images"

# Email settings
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587 # Standard port for TLS
EMAIL_ADDRESS = "" # Sender email
EMAIL_PASSWORD = "" # Use an App Password for security
RECIPIENT_EMAIL = "" # Recipient email

# Ensure the image directory exists
if not os.path.exists(IMAGE_DIR):
    os.makedirs(IMAGE_DIR)

def capture_images():
    """Captures a series of images from the USB camera at specified intervals."""
    print(f"Starting image capture of {NUM_IMAGES} images spaced by {INTERVAL_SECONDS} seconds...")
    cap = cv2.VideoCapture(CAMERA_INDEX)
    if not cap.isOpened():
        print("Error: Could not open camera.")
        return []

    image_files = []
    for i in range(NUM_IMAGES):
        ret, frame = cap.read()
        if ret:
            img_name = os.path.join(IMAGE_DIR, f"image_{i+1}.png")
            cv2.imwrite(img_name, frame)
            image_files.append(img_name)
            print(f"Captured {img_name}")
        else:
            print(f"Warning: Could not read frame {i+1}")
        
        if i < NUM_IMAGES - 1: # Don't sleep after the last image
            print(f"Waiting for {INTERVAL_SECONDS} seconds...")
            time.sleep(INTERVAL_SECONDS)

    cap.release()
    print("Image capture complete.")
    return image_files

def send_email(image_files):
    """Sends an email with captured images as attachments."""
    print("Attempting to send email...")
    msg = EmailMessage()
    msg['Subject'] = 'TARGET ACQUIRED'
    msg['From'] = EMAIL_ADDRESS
    msg['To'] = RECIPIENT_EMAIL
    msg.set_content('SEE ATTACHED TARGET IMAGES')

    for file_path in image_files:
        with open(file_path, 'rb') as f:
            file_data = f.read()
            file_name = os.path.basename(file_path)
            msg.add_attachment(file_data, maintype='image', subtype='png', filename=file_name)
        print(f"Attached {file_name}")

    try:
        with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
            server.starttls() # Secure the connection
            server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
            server.send_message(msg)
        print("Email sent successfully!")
    except smtplib.SMTPException as e:
        print(f"Error: Unable to send email. {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

def cleanup_images(image_files):
    """Deletes the captured images after sending the email."""
    for file_path in image_files:
        if os.path.exists(file_path):
            os.remove(file_path)
            print(f"Deleted {file_path}")
    # Optional: remove the directory if empty
    if not os.listdir(IMAGE_DIR):
        os.rmdir(IMAGE_DIR)
        print(f"Deleted directory {IMAGE_DIR}")

if __name__ == "__main__":
    images = capture_images()
    if images:
        send_email(images)
        cleanup_images(images)
    else:
        print("No images were captured. Email not sent.")
