## SaveManager — persists game state as JSON to user://savegame.json, auto-saves on state_changed.
extends Node

const SAVE_PATH: String = "user://savegame.json"


func _ready() -> void:
	GameState.state_changed.connect(_on_state_changed)


func save_game() -> void:
	var data: Dictionary = GameState.get_save_data()
	var file: FileAccess = FileAccess.open(SAVE_PATH, FileAccess.WRITE)
	if file == null:
		push_error("SaveManager: cannot open save file for writing")
		return
	file.store_string(JSON.stringify(data))
	file.close()


func load_game() -> void:
	if not FileAccess.file_exists(SAVE_PATH):
		return
	var file: FileAccess = FileAccess.open(SAVE_PATH, FileAccess.READ)
	if file == null:
		return
	var raw: String = file.get_as_text()
	file.close()
	var parsed: Variant = JSON.parse_string(raw)
	if parsed is Dictionary:
		GameState.apply_save_data(parsed)


func reset_game() -> void:
	if FileAccess.file_exists(SAVE_PATH):
		var dir: DirAccess = DirAccess.open("user://")
		if dir != null:
			dir.remove("savegame.json")
	GameState.apply_save_data({})


func _on_state_changed() -> void:
	save_game()
