#pragma once

#include "rtmp_client.h"
#include <cstdint>
#include <string>
#include <vector>

/**
 * RTMP sink that bridges encoded packets to an RTMP endpoint.
 * Ported from FLCKRtmpSink (UE5 LCKStreaming plugin).
 * Handles Annex-B to AVCC conversion, sequence headers, and FLV framing.
 */
class RtmpSink {
public:
    RtmpSink();
    ~RtmpSink();

    void SetRtmpUrl(const std::string& url);

    bool Open(uint32_t width, uint32_t height, uint32_t framerate,
              uint32_t sampleRate, uint32_t numChannels);
    void OnVideoFormatReady(const uint8_t* extraData, uint32_t extraDataSize);
    void OnAudioFormatReady(uint32_t sampleRate, uint32_t numChannels);
    void SendVideoPacket(const uint8_t* data, uint32_t size,
                         int64_t timestampMs, bool isKeyframe);
    void SendAudioPacket(const uint8_t* data, uint32_t size, int64_t timestampMs);
    void Close();
    bool IsOpen() const;

private:
    bool TryExtractAndSendSequenceHeader(const uint8_t* data, uint32_t size);
    static std::vector<uint8_t> ConvertAnnexBToAvcc(const uint8_t* data, uint32_t size);
    static std::vector<uint8_t> BuildAvccFromAnnexB(const uint8_t* sps, uint32_t spsSize,
                                                     const uint8_t* pps, uint32_t ppsSize);

    RtmpClient rtmpClient;
    std::string rtmpUrl;
    bool isOpen = false;
    bool videoHeaderSent = false;
    bool audioHeaderSent = false;
    uint32_t storedSampleRate = 48000;
    uint32_t storedNumChannels = 2;
};
