#pragma once
#include "AiDemoTypes.h"
#include "AiWebSocketClient.h"
#include <condition_variable>
#include <deque>
#include <functional>
#include <mutex>
#include <thread>
#include <atomic>

// Demo audio AI input port: SDK audio callback -> normalized PCM16 mono 16 kHz chunks -> WebSocket AI service.
// Step10 focuses on engineering reliability:
//   - Do not assume that the capture device really delivers 48k/2ch/16-bit.
//   - Normalize any HWS_AUDIO_FRAME format that the SDK exposes into PCM16 mono 16 kHz.
//   - Use smaller chunks and a larger queue to avoid audio loss while ASR is busy.
//   - Emit debug events for input format, queue pressure and timestamp gaps.
class AiAudioInputPort
{
public:
    typedef std::function<void(const AiDemoResult&)> ResultCallback;

    AiAudioInputPort();
    ~AiAudioInputPort();

    void SetResultCallback(ResultCallback cb);
    void Start(const AiAudioInputConfig& cfg);
    void Stop();
    bool IsRunning() const;

    // Called from SDK audio callback. This function must not block the SDK audio capture thread.
    void PushAudioFrame(const HWS_AUDIO_FRAME* frame);

private:
    void WorkerThread();
    bool ConvertFrameToMono16k(const HWS_AUDIO_FRAME* frame, std::vector<short>* outSamples);
    void QueueReadyChunksLocked();
    void PostDebugResult(const std::string& text, long long timestamp100ns, long long chunkIndex = -1);
    void MaybeLogInputFormatLocked(const HWS_AUDIO_FRAME* frame, int dstSamples);
    void MaybeCheckInputTimestampLocked(const HWS_AUDIO_FRAME* frame);

private:
    mutable std::mutex lock_;
    std::condition_variable cv_;
    std::deque<AiCapturedAudioChunk> queue_;
    std::vector<short> pendingSamples_;
    long long pendingStartTimestamp100ns_;
    long long nextChunkIndex_;
    std::thread worker_;
    std::atomic<bool> running_;
    std::atomic<bool> stopping_;
    AiAudioInputConfig config_;
    ResultCallback resultCb_;

    // Step10 diagnostics.
    bool inputFormatLogged_;
    long long pushedInputFrames_;
    long long convertedInputSamples_;
    long long droppedQueueChunks_;
    long long maxObservedQueueDepth_;
    long long expectedNextInputTimestamp100ns_;
    long long timestampGapWarnings_;
    long long producedChunks_;
    long long sentChunks_;
    long long sendFailures_;
    long long receivedResults_;
    long long maxSendRoundtripMs_;
    long long lastProducerReportChunk_;
    long long lastSenderReportChunk_;
};
