#ifndef __VIDEO_RECORDER_H__
#define __VIDEO_RECORDER_H__

#include "basic/timer.h"
#include "capturer/video/VideoCaptureManager.h"
using namespace avrecorder::video;

#include "muxer/av_muxer.h"
#include <deque>
#include <string>
// #include <condition_variable>
// #include <queue>

class VideoRecorder {
public:
    bool Open(HWND srcHwnd, Encoder<MediaType::VIDEO>::Param& param, CaptureMethod method);
    bool Open(int monitorIdx, Encoder<MediaType::VIDEO>::Param& param, CaptureMethod method);
    bool LoadMuxer(AvMuxer& muxer);
    bool UnloadMuxer(AvMuxer& muxer);
    bool StartRecord();
    void StopRecord();
    AVFrame* GetRenderFrame();
    void Close();
    void SetIsDrawCursor(bool isDraw) { _capturer.setDrawCursor(isDraw); }
    bool IsCaptureOverload() const { return _captureTimer.IsOverload(); }
    double GetLossRate();
    void SetCaptureSource(HWND srcHwnd, CaptureMethod method);
    void SetCaptureSource(int monitorIdx, CaptureMethod method);
    // 新增：获取指定muxer对应的视频编码器名称
    std::string GetEncoderNameForMuxer(AvMuxer& muxer);

private:
    struct MuxerInfo {
        AvMuxer* muxer;
        int streamIndex;
        MuxerInfo(AvMuxer* m, int idx) : muxer(m), streamIndex(idx) {}
    };
    
    static constexpr int kCanvasWidth = 1920;
    static constexpr int kCanvasHeight = 1080;
    bool _Open(Encoder<MediaType::VIDEO>::Param& param);
    VideoCaptureManager _capturer;
    std::vector<MuxerInfo> _muxers;
    std::mutex _muxersMtx;
    bool _isRecord = false;
    AVFrame* _encodeFrame = nullptr;
    AVFrame* _renderFrame = nullptr;
    Encoder<MediaType::VIDEO>::Param _param;
    Timer _captureTimer;
    Timer _muxTimer;
    std::mutex _renderMtx;
    std::mutex _lossMtx;
    uint64_t _totalPts = 0;
    uint64_t _lossPts = 0;
    // 滑动窗口丢帧统计
    static constexpr int LOSS_WINDOW = 100;
    std::deque<bool> _lossHistory;
};
#endif
