#ifndef AV_RECORDER_AUDIO_RECORDER_H
#define AV_RECORDER_AUDIO_RECORDER_H

#include "recorder_abstract_recorder.h"
#include "../capture/capture_audio_capturer.h"
#include "../codec/codec_audio_encoder.h"
#include "../muxer/muxer_abstract_muxer.h"
#include "../utils/utils_thread_pool.h"
#include <vector>
#include <memory>
#include <thread>
#include <atomic>
#include <deque>
#include <condition_variable>

namespace av {
namespace recorder {

/**
 * 音频录制器参数
 */
struct AudioRecorderParams : public RecorderParams {
    // 音频采集参数
    capture::CapturerType capturerType = capture::CapturerType::AUDIO_MIC;
    std::string deviceId;               // 音频设备ID
    uint32_t sampleRate = 44100;        // 采样率
    uint32_t channels = 2;              // 声道数
    uint32_t bitsPerSample = 16;        // 位深度
    AVSampleFormat sampleFormat = AV_SAMPLE_FMT_S16;
    
    // 编码参数
    std::string codecName = "aac";      // 编码器名称
    uint32_t bitrate = 128000;          // 比特率
    
    // 混音参数
    bool enableMixing = false;          // 是否启用混音
    std::vector<std::string> mixDevices; // 混音设备列表
    float volumeScale = 1.0f;           // 音量缩放
    
    AudioRecorderParams() {
        mediaType = MediaType::AUDIO;
        format = "mp4";
    }
};

/**
 * 音频录制器
 * 支持多设备采集、混音、编码和输出
 */
class AudioRecorder : public AbstractRecorder {
public:
    AudioRecorder();
    virtual ~AudioRecorder();

    // 实现基类接口
    ErrorCode initialize(const RecorderParams& params) override;
    ErrorCode startRecording() override;
    ErrorCode stopRecording() override;
    ErrorCode pauseRecording() override;
    ErrorCode resumeRecording() override;
    void close() override;

    // 音频特定功能
    /**
     * 设置音量缩放
     */
    void setVolumeScale(float scale);
    
    /**
     * 获取音频电平
     */
    float getAudioLevel() const;
    
    /**
     * 添加音频设备
     */
    ErrorCode addAudioDevice(const std::string& deviceId, capture::CapturerType type);
    
    /**
     * 移除音频设备
     */
    ErrorCode removeAudioDevice(const std::string& deviceId);
    
    /**
     * 获取可用音频设备列表
     */
    std::vector<std::string> getAvailableDevices(capture::CapturerType type) const;

protected:
    bool validateParams(const RecorderParams& params) override;

private:
    /**
     * 音频处理线程
     */
    void audioProcessingThread();
    
    /**
     * 混音处理
     */
    AVFramePtr mixAudioFrames(const std::vector<AVFramePtr>& frames);
    
    /**
     * 音频帧回调
     */
    void onAudioFrameCaptured(const AVFramePtr& frame, size_t capturerIndex);
    
    /**
     * 编码完成回调
     */
    void onAudioPacketEncoded(const AVPacketPtr& packet);
    
    /**
     * 初始化采集器
     */
    ErrorCode initializeCapturers();
    
    /**
     * 初始化编码器
     */
    ErrorCode initializeEncoder();
    
    /**
     * 初始化复用器
     */
    ErrorCode initializeMuxer();
    
    /**
     * 清理资源
     */
    void cleanup();

private:
    AudioRecorderParams audioParams_;
    
    // 采集器
    std::vector<std::unique_ptr<capture::AudioCapturer>> capturers_;
    
    // 编码器
    std::unique_ptr<codec::AudioEncoder> encoder_;
    
    // 复用器
    std::unique_ptr<muxer::AbstractMuxer> muxer_;
    
    // 线程池
    std::unique_ptr<utils::ThreadPool> threadPool_;
    
    // 音频处理线程
    std::unique_ptr<std::thread> processingThread_;
    std::atomic<bool> shouldStop_;
    
    // 音频帧队列
    struct AudioFrameData {
        AVFramePtr frame;
        size_t capturerIndex;
        std::chrono::steady_clock::time_point timestamp;
        
        // 默认构造函数
        AudioFrameData() = default;
        
        // 移动构造函数
        AudioFrameData(AudioFrameData&& other) noexcept
            : frame(std::move(other.frame))
            , capturerIndex(other.capturerIndex)
            , timestamp(other.timestamp) {}
        
        // 移动赋值运算符
        AudioFrameData& operator=(AudioFrameData&& other) noexcept {
            if (this != &other) {
                frame = std::move(other.frame);
                capturerIndex = other.capturerIndex;
                timestamp = other.timestamp;
            }
            return *this;
        }
        
        // 禁用拷贝构造函数和拷贝赋值运算符
        AudioFrameData(const AudioFrameData&) = delete;
        AudioFrameData& operator=(const AudioFrameData&) = delete;
    };
    
    std::deque<AudioFrameData> frameQueue_;
    std::mutex queueMutex_;
    std::condition_variable queueCondition_;
    
    // 混音相关
    float volumeScale_;
    mutable std::mutex audioLevelMutex_;
    float currentAudioLevel_;
    
    // 同步相关
    std::mutex capturerMutex_;
    std::atomic<bool> isPaused_;
    
    // 统计信息
    std::atomic<uint64_t> processedSamples_;
    std::chrono::steady_clock::time_point lastProcessTime_;
};

} // namespace recorder
} // namespace av

#endif // AV_RECORDER_AUDIO_RECORDER_H