# Install necessary libraries:
# pip install SpeechRecognition requests pusher flask
# pip install flask-cors
# CORS(app, resources={r"/stop": {"origins": "http://example.com"}}) 

import speech_recognition as sr
import requests
import time
import sys
import threading
from flask import Flask, request, jsonify
from flask_cors import CORS
import pusher

# Define the endpoints
gptEndpoint = "https://www.vortext.ca/processKioskInquiry.cfm"

# Replace with your Pusher app credentials
pusher_client = pusher.Pusher(
    app_id='1899708',
    key='f3fa822541d632006b56',
    secret='b9a512076981d23e5e30',
    cluster='mt1',
    ssl=True  # Use SSL for secure connections
)

# Initialize the speech recognizer and microphone
recognizer = sr.Recognizer()
microphone = sr.Microphone()

# Flask app
app = Flask(__name__)
CORS(app)  # This enables CORS for all routes


# Global flag to control microphone listening
listening = False

def listen_and_process():
    global listening
    with microphone as source:
        print("Starting... Please wait.")
        recognizer.adjust_for_ambient_noise(source)
        print("Listening...")
        while listening:
            try:
                audio = recognizer.listen(source)
                text = recognizer.recognize_google(audio)
                print(f"Recognized Text: {text}")
                
                pusher_client.trigger('voice-search-channel', 'voice-search-channel-stop-speaker-button', {})
                # Send the text to gptEndpoint
                response = requests.post(gptEndpoint, json={"input": text})
                if response.status_code == 200:
                    result = response.json().get("output", "")

                    if result:
                        print(f"Received: {result}")
                        pusher_client.trigger('voice-search-channel', 'voice-search-channel-event', {'unit': f'{result}'})
                    else:
                        print("No response text received from gptEndpoint.")
                else:
                    print(f"Error contacting gptEndpoint: {response.status_code}")

            except sr.UnknownValueError:
                print("-")
            except sr.RequestError as e:
                print(f"Speech Recognition error: {e}")
            except requests.RequestException as e:
                print(f"HTTP request error: {e}")
            time.sleep(1)

@app.route("/start", methods=["POST", "GET"])
def start_listening():
    global listening
    if not listening:
        listening = True
        threading.Thread(target=listen_and_process).start()
        return jsonify({"status": "Listening started"})
    else:
        return jsonify({"status": "Already listening"})

@app.route("/stop", methods=["POST", "GET"])
def stop_listening():
    global listening
    if listening:
        listening = False
        return jsonify({"status": "Listening stopped"})
    else:
        return jsonify({"status": "Not currently listening"})

@app.route("/trigger", methods=["POST"])
def trigger_pusher_event():
    data = request.get_json()
    unit = data.get("unit", "default-unit")
    pusher_client.trigger('voice-search-channel', 'voice-search-channel-event', {'unit': unit})
    return jsonify({"status": f"Sent: {unit}"})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

