import serial
import sys
import subprocess
import time

# ========= CONFIGURE THESE =========
# Replace this with the correct port for your Arduino:
#   - Windows: something like "COM3"
#   - Mac/Linux: something like "/dev/tty.usbmodemXXXX" or "/dev/ttyACM0"
PORT = "COM3"  # CHANGE THIS

BAUD = 9600

# Path to your audio file:
# Example Windows: r"C:\Users\You\Music\rock_sound.m4a"
# Example Mac: "/Users/you/Music/rock_sound.m4a"
AUDIO_FILE = r"C:\Users\sommi\OneDrive\Documents\ME 411\project\the rock sound.m4a"# CHANGE THIS
# ===================================

def play_audio(path):
  if sys.platform.startswith("win"):
    # Windows: use 'start' to open with default player
    subprocess.Popen(['start', '', path], shell=True)
  elif sys.platform == "darwin":
    # macOS: 'open' uses default app
    subprocess.Popen(['open', path])
  else:
    # Linux: try xdg-open
    subprocess.Popen(['xdg-open', path])

def main():
  print(f"Opening serial port {PORT} at {BAUD} baud...")
  ser = serial.Serial(PORT, BAUD, timeout=1)
  time.sleep(2)  # give Arduino time to reset after serial open

  print("Listening for 'PLAY' from Arduino...")
  try:
    while True:
      line = ser.readline().decode(errors="ignore").strip()
      if not line:
        continue

      print(f"Serial: {line}")

      if line == "PLAY":
        print("=> Trigger received! Playing audio...")
        play_audio(AUDIO_FILE)

  except KeyboardInterrupt:
    print("Exiting...")
  finally:
    ser.close()

if __name__ == "__main__":
  main()
