import time

from retell import Retell
import websocket
import threading
import pyaudio

# Calculate frames per 100 ms
frame_duration_ms = 100
frames_per_buffer = int((24000 * frame_duration_ms) / 1000)

p = pyaudio.PyAudio()
input_stream = p.open(format=pyaudio.paInt16,  # 16-bit signed integers
                      channels=1,  # Mono audio
                      rate=24000,  # 24000 Hz sample rate
                      input=True,
                      frames_per_buffer=frames_per_buffer)
output_stream = p.open(format=pyaudio.paInt16,
                       channels=1,
                       rate=24000,
                       output=True,
                       frames_per_buffer=frames_per_buffer)
print("Created in and out audio streams")


def on_message(ws, message):
    print("Received Audio")
    try:
        output_stream.write(message)
    except Exception as e:
        print("Failed to play message:", e)


def on_error(ws, error):
    print("Received error in on_error:", error)


def on_open(ws):
    print("Start on_open")

    def run(*args):
        try:
            last_time_sent = time.time()
            while True:
                print("Listening audio from mic")
                try:
                    current_time = time.time()
                    data = input_stream.read(frames_per_buffer, exception_on_overflow=False)
                    print("Sending data to WS")
                    ws.send(data)
                    time_elapsed = current_time - last_time_sent
                    print(f"Data sent to WS. Time since last send: {time_elapsed:.2f} seconds")
                    last_time_sent = current_time
                except IOError as e:
                    print("Buffer overflow:", e)
                print("Send data to socket")
        except Exception as e:
            print("Streaming stopped", e)
        finally:
            input_stream.stop_stream()
            input_stream.close()
            p.terminate()

    thread = threading.Thread(target=run)
    thread.start()
    print("Finished on_open")


def on_close(ws, close_status_code, close_msg):
    print("### start close")
    input_stream.stop_stream()
    input_stream.close()

    output_stream.stop_stream()
    output_stream.close()
    print("### closed ###")


def connect_to_call(call_id: str) -> None:
    # websocket.enableTrace(True)

    ws = websocket.WebSocketApp(f"wss://api.retellai.com/audio-websocket/{call_id}",
                                on_open=on_open,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)

    ws.run_forever()
    print("Finished connect to call")


def create_call() -> str:
    client = Retell(
        # Find the key in dashboard
        api_key="<KEY>",
    )

    call = client.call.register(
        agent_id="396d2e8b00645cc702966f67d5ce2e35",
        audio_encoding="s16le",
        audio_websocket_protocol="web",
        sample_rate=24000,
    )
    print(f"Call started. Id {call.call_id}, agent id {call.agent_id}")
    return call.call_id


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    id: str = create_call()
    connect_to_call(call_id=id)
