extends Node

const SAVE_DIR: String = "user://saves/"

func ensure_dir() -> void:
  DirAccess.make_dir_recursive_absolute(SAVE_DIR)

func save_path(slot: String) -> String:
  return SAVE_DIR + slot + ".save"

func save_run(slot: String, payload: Dictionary) -> bool:
  ensure_dir()
  var f := FileAccess.open(save_path(slot), FileAccess.WRITE)
  if f == null:
    push_error("SaveLoad: cannot open %s for write" % slot)
    return false
  f.store_string(JSON.stringify(payload, "  "))
  f.close()
  return true

func load_run(slot: String) -> Dictionary:
  var path := save_path(slot)
  if not FileAccess.file_exists(path):
    return {}
  var f := FileAccess.open(path, FileAccess.READ)
  var text := f.get_as_text()
  f.close()
  var data: Variant = JSON.parse_string(text)
  if typeof(data) != TYPE_DICTIONARY:
    return {}
  return data

func list_slots() -> Array[String]:
  ensure_dir()
  var out: Array[String] = []
  var d := DirAccess.open(SAVE_DIR)
  if d == null:
    return out
  d.list_dir_begin()
  var fname := d.get_next()
  while fname != "":
    if not d.current_is_dir() and fname.ends_with(".save"):
      out.append(fname.trim_suffix(".save"))
    fname = d.get_next()
  d.list_dir_end()
  return out
