import RPi.GPIO as GPIO
import time
import subprocess
import threading
import sys

# GPIO pin setup
PIR_PIN = 25  # PIR sensor connected to GPIO 25
LED_PIN = 16  # LED connected to GPIO 16

# Paths to the scripts you want to launch
SCRIPT1_PATH = "/home/dj/Desktop/intrusion-detector/main.py"
SCRIPT2_PATH = "/home/dj/Desktop/intrusion-detector/send.py"

def setup_gpio():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(PIR_PIN, GPIO.IN)
    GPIO.setup(LED_PIN, GPIO.OUT)
    GPIO.output(LED_PIN, GPIO.HIGH)  # Turn LED on initially

def run_script(script_path):
    try:
        subprocess.run(["python3", script_path], check=True)
    except subprocess.CalledProcessError as e:
        print(f"Error running {script_path}: {e}")
    except FileNotFoundError:
        print(f"Script not found: {script_path}")

def launch_scripts():
    # Launch both scripts simultaneously using threading
    thread1 = threading.Thread(target=run_script, args=(SCRIPT1_PATH,))
    thread2 = threading.Thread(target=run_script, args=(SCRIPT2_PATH,))
    
    thread1.start()
    thread2.start()
    
    thread1.join()
    thread2.join()

def main():
    setup_gpio()
    print("PIR Motion Sensor initialized. LED is ON. Waiting for motion...")
    
    try:
        while True:
            if GPIO.input(PIR_PIN):
                print("Motion detected! Turning LED OFF and launching scripts...")
                GPIO.output(LED_PIN, GPIO.LOW)  # Turn LED off
                launch_scripts()
                print("Scripts completed. Exiting program.")
                GPIO.cleanup()  # Clean up GPIO settings
                sys.exit(0)  # Exit the script after first motion detection
            time.sleep(0.1)  # Small delay to prevent CPU overload
            
    except KeyboardInterrupt:
        print("\nExiting program...")
    finally:
        GPIO.cleanup()  # Clean up GPIO settings

if __name__ == "__main__":
    main()
