#pragma once

#include "app/app_state.hpp"

#include <nlohmann/json.hpp>

#include <filesystem>
#include <optional>
#include <string>

namespace lm {

class Database;

class StateRepository
{
public:
  StateRepository(std::filesystem::path data_path, Database& db);

  AppState& app() { return app_; }
  const AppState& app() const { return app_; }

  bool load();
  bool save() const;
  bool saveAppState();
  void ensureSchema();

  bool saveProfile(const nlohmann::json& profile);
  void reloadActiveCache();
  bool deleteProfile(const std::string& id);
  std::optional<nlohmann::json> loadProfileById(const std::string& id) const;

private:
  AppState app_;
  Database& db_;

  std::filesystem::path modelsDir() const;
  std::filesystem::path profileFilePath(const std::string& id) const;

  std::optional<nlohmann::json> loadProfileFromDisk(const std::string& id) const;
  bool saveProfileToDisk(const nlohmann::json& profile) const;
  bool deleteProfileFile(const std::string& id) const;

  void loadActiveCache();
  bool persistActiveProfile();
  nlohmann::json globalStateForDisk(const nlohmann::json& state) const;
  void stripInlineProfiles(nlohmann::json& state) const;
  void migrateStorage();
  void bootstrapDefaultState();
};

}  // namespace lm
