#pragma once

#include <aaudio/AAudio.h>
#include <atomic>
#include <cstdint>

// Lock-free ring buffer for audio samples (interleaved stereo int16)
class RingBuffer {
public:
    static constexpr size_t CAPACITY = 8192; // frames (each frame = 2 samples L+R)

    void push(const int16_t* data, size_t frames);
    size_t pop(int16_t* out, size_t frames);
    size_t available() const;

private:
    int16_t buffer_[CAPACITY * 2]{}; // stereo
    std::atomic<size_t> read_pos_{0};
    std::atomic<size_t> write_pos_{0};
};

class AudioEngine {
public:
    bool start(int32_t sampleRate);
    void stop();
    void pushSamples(const int16_t* data, size_t frames);
    void setEnabled(bool enabled) { enabled_.store(enabled); }

    RingBuffer& ringBuffer() { return ring_buffer_; }
    bool isEnabled() const { return enabled_.load(); }

private:
    AAudioStream* stream_ = nullptr;
    RingBuffer ring_buffer_;
    std::atomic<bool> enabled_{true};

    static aaudio_data_callback_result_t dataCallback(
        AAudioStream* stream, void* userData, void* audioData, int32_t numFrames);
};
