import RPi.GPIO as GPIO
import time
from audio_to_text import AudioToText
from function_handler import handle_command
from text_to_audio import TextToAudio
from oled_display import OLEDDisplay



oled = OLEDDisplay()
GPIO.setmode(GPIO.BCM)
SWITCH_PIN = 4    # BOARD pin 7
LED_PIN = 6      # BOARD pin 31
GPIO.setup(SWITCH_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)  # Internal pull-up for the switch
GPIO.setup(LED_PIN, GPIO.OUT)

# Initialize audio listener and speaker
audio_listener = AudioToText()
speaker = TextToAudio()

def main():
    
    print("Waiting for switch to be turned ON...")
    oled.show_message("Waiting for switch\nON...")

    while GPIO.input(SWITCH_PIN) == GPIO.HIGH:
        print("Switch is OFF. Waiting...")
        time.sleep(0.1)

    print("Switch is ON. Starting assistant...")
    oled.show_message("Switch is ON.\nStarting assistant...")
    speaker.speak("Hi there buddy, have a good day")
    GPIO.output(LED_PIN, GPIO.HIGH)

    try:
        while True:
            # Wait for wake word
            print("Listening for wake word...")
            oled.show_message("Listening for\nwake word...")
            spoken_text = audio_listener.listen(duration=3).lower()
            print(spoken_text)

            if any(phrase in spoken_text for phrase in ["hey charli", "hey charlie"]):
                print("Wake word detected.")
                oled.show_message("Wake word\ndetected")

                # Listen for command
                print("Waiting for command...")
                oled.show_message("Waiting for\ncommand...")
                speaker.speak("Waiting for command...")
                command = audio_listener.listen(duration=3).lower()
                print("Recognized command after wake word:", command)
                # Handle the command
                handle_command(command, audio_listener, speaker)
                
                print("Command handled. Listening again...")
                oled.show_message("Ready for\nnext command")

    except KeyboardInterrupt:
        print("Program interrupted manually.")
        oled.show_message("Interrupted.\nExiting...")

    finally:
        GPIO.output(LED_PIN, GPIO.LOW)
        GPIO.cleanup()
        print("GPIO cleaned up. Program exited.")
        oled.show_message("GPIO cleaned\nProgram exited")

if __name__ == "__main__":
    main()
