#pragma once

#include <Arduino.h>
#include <SPIFFS.h>
#include "GnssTypes.h"

namespace field_qa {

class StorageManager {
 public:
  bool mount();
  bool begin(const char* runId);
  bool startLog(const char* runId, const char* bootTimestampUtc);
  bool mounted() const;
  bool ready() const;
  const char* currentPath() const;
  const char* lastError() const;
  bool fileOpen() const;
  size_t bufferedBytes() const;
  size_t logFileCount() const;
  void appendSampleTsv(const GnssSample& sample, const char* runId, const char* bootTimestampUtc);
  void appendSatelliteTsv(const GnssSample& sample,
                          const SatelliteInfo* satellites,
                          size_t satelliteCount,
                          const char* runId,
                          const char* bootTimestampUtc);
  void flush();
  void close();
  void listFiles(Stream& out);
  void catFile(Stream& out, const char* path);
  void eraseLogs(Stream& out);

 private:
  bool ensureDir();
  bool openFile();
  void writeHeader(const char* runId, const char* bootTimestampUtc);
  String makeFilePath(const char* runId) const;
  void appendLine(const String& line);

  bool m_ready = false;
  String m_path;
  String m_lastError;
  File m_file;
  String m_buffer;
};

}  // namespace field_qa
