#pragma once

#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>

struct CapturePacket {
    std::size_t packet_index = 0;
    std::size_t channel_count = 2;
    bool has_di1_trace = false;
    std::vector<double> ch1;
    std::vector<double> ch2;
    std::vector<uint8_t> di1;
};

class CaptureFileWriter {
public:
    CaptureFileWriter(std::string csv_path,
                      std::string svg_path,
                      std::string live_html_path,
                      std::string live_json_path);

    void write(const std::vector<CapturePacket>& packets,
               double frame_freq_hz,
               double nominal_range_v) const;

    void initialize_live_plot() const;
    void initialize_csv(std::size_t channel_count, bool has_di1_trace) const;
    void append_csv_packet(const CapturePacket& packet,
                           double frame_freq_hz,
                           std::size_t& global_frame_index) const;

    void update_live_plot(const CapturePacket& packet,
                          std::size_t packets_seen,
                          double packets_per_second,
                          double frame_freq_hz,
                          const std::string& close_reason,
                          std::size_t zeroed_samples,
                          std::size_t stored_samples) const;

    const std::string& live_html_path() const;
    const std::string& live_json_path() const;

private:
    void finalize_csv_from_spool(double frame_freq_hz) const;
    void write_svg(const std::vector<CapturePacket>& packets,
                   double frame_freq_hz,
                   double nominal_range_v) const;

    std::string csv_path_;
    std::string svg_path_;
    std::string live_html_path_;
    std::string live_json_path_;
};
