#pragma once

#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>

class TtyProtocolWriter {
public:
    struct StatsSnapshot {
        std::uint64_t frames_written = 0;
        std::uint64_t frames_dropped = 0;
        std::uint64_t ring_overflows = 0;
    };

    TtyProtocolWriter(std::string path, std::size_t ring_capacity_bytes);
    ~TtyProtocolWriter();

    TtyProtocolWriter(const TtyProtocolWriter&) = delete;
    TtyProtocolWriter& operator=(const TtyProtocolWriter&) = delete;
    TtyProtocolWriter(TtyProtocolWriter&& other) noexcept = delete;
    TtyProtocolWriter& operator=(TtyProtocolWriter&& other) noexcept = delete;

    void emit_packet_start(uint16_t marker = 0x000A);
    void emit_step(uint16_t index, int16_t ch1_avg, int16_t ch2_avg);
    void enqueue_encoded_frames(const uint16_t* words, std::size_t frame_count);
    StatsSnapshot stats() const;

    const std::string& path() const;
    void throw_if_failed() const;
    void shutdown();

private:
    void enqueue_frame(uint16_t word0, uint16_t word1, uint16_t word2, uint16_t word3);
    void worker_loop();

    std::string path_;

    struct Impl;
    std::unique_ptr<Impl> impl_;
};
