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

#include <k230_audio.h>
#include <k230_wave.h>

static std::atomic<bool> g_exit_requested(false);

// Signal handler for graceful exit
static void signal_handler(int signal) {
    std::cout << "Received interrupt signal, stopping..." << std::endl;
    g_exit_requested.store(true);
}

// Play WAV file
static void play_audio(const std::string& filename) {
    try {
        // Open WAV file
        auto wf = open_read(filename);
        int channels = wf->get_channels();
        int sampwidth = wf->get_sampwidth();
        int framerate = wf->get_framerate();
        int chunk = framerate / 25;  // Calculate appropriate chunk size

        ArduinoAudio audio;

        // Create audio output stream
        AudioFormat format = static_cast<AudioFormat>(audio.get_format_from_width(sampwidth));
        AudioStream* stream = audio.open(framerate, channels, format,
                                   false, true,   // Output stream
                                   -1, -1,        // Default device
                                   true,          // Enable codec
                                   chunk,         // Frames per buffer
                                   false);        // Do not start immediately

        // Set volume
        stream->volume(85);
        std::cout << "Output volume set to 85" << std::endl;

        // Start stream
        stream->start_stream();

        std::cout << "Start playing: " << filename << std::endl;

        // Play audio data
        auto data = wf->read_frames(chunk);
        while (!data.empty() && !g_exit_requested.load()) {
            // Convert char data to uint8_t
            std::vector<uint8_t> audio_data(data.begin(), data.end());
            stream->write(audio_data);

            data = wf->read_frames(chunk);
        }

        // Stop stream
        stream->stop_stream();

        // Clean up resources
        audio.close(stream);
        wf->close();

        std::cout << "Playback finished" << std::endl;

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

void setup()
{
    play_audio("/data/test.wav");  //Play WAV file
}

void loop()
{

}