// 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);
}

// Record audio and save as WAV file
static void record_audio(const std::string& filename, int duration_seconds) {
    const int CHUNK = 44100 / 25;  // Audio chunk size
    const AudioFormat FORMAT = paInt16;  // 16-bit sample precision
    const int CHANNELS = 2;        // Stereo
    const int RATE = 44100;        // Sample rate

    try {
        ArduinoAudio audio;

        // Create audio input stream
        AudioStream* stream = audio.open(RATE, CHANNELS, FORMAT,
                                   true, false,  // Input stream
                                   -1, -1,       // Default device
                                   true,         // Enable codec
                                   CHUNK,        // Frames per buffer
                                   false);       // Do not start immediately

        // Set volume
        stream->volume(70, LEFT);
        stream->volume(85, RIGHT);
        std::cout << "Input volume set" << std::endl;

        // Enable audio 3A feature: Automatic Noise Suppression
        stream->enable_audio3a(AUDIO_3A_ENABLE_ANS);
        std::cout << "Enabled audio 3A: ANS" << std::endl;

        // Start stream
        stream->start_stream();

        std::vector<std::vector<uint8_t>> frames;
        int total_chunks = (RATE / CHUNK) * duration_seconds;

        std::cout << "Start recording for " << duration_seconds << " seconds..." << std::endl;

        // Collect audio data
        for (int i = 0; i < total_chunks && !g_exit_requested.load(); ++i) {
            std::vector<uint8_t> data;
            if (stream->read(data, 0, true) == 0) {
                frames.push_back(std::move(data));
            }

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

        // Stop stream
        stream->stop_stream();
        std::cout << "Recording finished, saving to file..." << std::endl;

        // Save as WAV file
        auto wf = open_write(filename);
        wf->set_channels(CHANNELS);
        wf->set_sampwidth(audio.get_sample_size(FORMAT));
        wf->set_framerate(RATE);

        // Merge all frame data
        std::vector<char> all_data;
        for (const auto& frame : frames) {
            all_data.insert(all_data.end(),
                          reinterpret_cast<const char*>(frame.data()),
                          reinterpret_cast<const char*>(frame.data() + frame.size()));
        }

        wf->write_frames(all_data);
        wf->close();

        // Clean up resources
        audio.close(stream);

        std::cout << "Audio saved to: " << filename << std::endl;

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


void setup()
{
    record_audio("/data/test.wav", 15); // Record WAV file

}

void loop()
{

}