#include <iostream>
#include <vector>
#include <string>
#include <thread>
#include <chrono>
#include <signal.h>
#include <atomic>

#include <k230_audio.h>

// Real-time audio loopback (capture and play back immediately)
static void loop_audio(int duration_seconds) {
    const int CHUNK = 44100 / 25;
    const AudioFormat FORMAT = paInt16;
    const int CHANNELS = 2;
    const int RATE = 44100;

    try {
        ArduinoAudio audio;

        // Create audio input stream
        AudioStream* input_stream = audio.open(RATE, CHANNELS, FORMAT,
                                         true, false,   // Input stream
                                         -1, -1,        // Default device
                                         true,          // Enable codec
                                         CHUNK,
                                         false);

        // Create audio output stream
        AudioStream* output_stream = audio.open(RATE, CHANNELS, FORMAT,
                                          false, true,  // Output stream
                                          -1, -1,       // Default device
                                          true,         // Enable codec
                                          CHUNK,
                                          false);

        // Set input stream parameters
        input_stream->volume(70, LEFT);
        input_stream->volume(85, RIGHT);
        input_stream->enable_audio3a(AUDIO_3A_ENABLE_ANS);

        // Set output stream parameters
        output_stream->volume(85);

        // Start streams
        input_stream->start_stream();
        output_stream->start_stream();

        int total_chunks = (RATE / CHUNK) * duration_seconds;
        std::cout << "Start audio loop for " << duration_seconds << " seconds..." << std::endl;

        // Real-time loopback processing
        for (int i = 0; i < total_chunks; ++i) {
            std::vector<uint8_t> data;
            if (input_stream->read(data, 0, true) == 0) {
                output_stream->write(data);
            }

            // Display progress
            if (i % 50 == 0) {
                std::cout << "Looping... " << (i * 100 / total_chunks) << "%" << std::endl;
            }
        }

        // Stop streams
        input_stream->stop_stream();
        output_stream->stop_stream();

        // Clean up resources
        audio.close(input_stream);
        audio.close(output_stream);

        std::cout << "Audio loopback finished" << std::endl;

    } catch (const std::exception& e) {
        std::cerr << "Error in loopback_audio: " << e.what() << std::endl;
    }
}

void setup()
{
    loop_audio(15);  // Loopback for 15 seconds
}

void loop()
{

}