#pragma once

#include <cstdint>
#include <functional>
#include <mutex>
#include <string>
#include <vector>

struct CortexSampleEntry {
    uint8_t track;       // 0=video, 1=audio
    uint8_t flags;       // bit0=keyframe
    uint32_t size;
    int64_t timestampUs;
    std::vector<uint8_t> data;
};

class CortexRecorder {
public:
    using SegmentCallback = std::function<void(const std::string& segPath,
                                                const uint8_t* keyframeData,
                                                uint32_t keyframeSize)>;

    CortexRecorder() = default;
    ~CortexRecorder() = default;

    void Configure(int w, int h, uint32_t sampleRate, uint32_t channels, int audioBitrate);
    void SetVideoFormat(const uint8_t* sps_pps, uint32_t size);
    void SetAudioFormat(const uint8_t* aac_config, uint32_t size);

    void StartSession(const std::string& sessionDir);
    void StopSession();

    void FeedVideoPacket(const uint8_t* data, uint32_t size, int64_t timestampUs, bool isKeyframe);
    void FeedAudioPacket(const uint8_t* data, uint32_t size, int64_t timestampUs);

    void SetMaxDurationMinutes(int minutes);
    void SetSegmentCallback(SegmentCallback cb);

    bool IsActive() const;

private:
    void FinalizeCurrentSegment();
    void TrimOldSegments();
    std::string MakeSegmentPath(int index) const;

    std::mutex mutex;
    bool active = false;

    int videoWidth = 0;
    int videoHeight = 0;
    uint32_t sampleRate = 48000;
    uint32_t audioChannels = 2;
    int audioBitrate = 128000;

    std::vector<uint8_t> videoCodecConfig;  // SPS+PPS
    std::vector<uint8_t> audioCodecConfig;  // AAC config

    std::string sessionDir;
    int segmentIndex = 0;
    int64_t segmentStartUs = 0;
    std::vector<CortexSampleEntry> currentSamples;
    std::vector<uint8_t> firstKeyframeData;  // first keyframe NAL in current segment

    int maxDurationMinutes = 10;

    static constexpr int64_t SEGMENT_DURATION_US = 30000000LL; // 30 seconds

    SegmentCallback segmentCallback;
};
