import json
import shutil
import tempfile
from pathlib import Path

from components.sud import Sud, SudState

# Console-only walkthrough of Sud.save()/load() (no plot - there's no
# numeric data here, just JSON plumbing). Runs against a scratch copy of a
# real sud.json so sude/sud_0010.json itself is never touched.

if __name__ == '__main__':
	with tempfile.TemporaryDirectory() as tmp:
		path = Path(tmp) / "sud.json"
		shutil.copy("sude/sud_0010.json", path)

		sud = Sud(str(path))
		print(f"Loaded '{sud.name}', {len(sud.schedule)} steps")

		doc = sud.save()
		assert doc['Name'] == sud.name
		print("save() returned the on-disk document")

		sud.state = SudState.RAMPING
		assert sud.load(doc) is False
		print("load() refused while RAMPING")

		sud.state = SudState.IDLE
		doc['Name'] = 'Sud-Renamed'
		doc['steps'][0]['descr'] = 'Edited step'
		assert sud.load(doc) is True
		assert sud.name == 'Sud-Renamed'
		assert sud.schedule[0]['descr'] == 'Edited step'
		assert sud.state == SudState.IDLE
		print("load() applied the edit and reset to IDLE")

		on_disk = json.loads(path.read_text())
		assert on_disk['Name'] == 'Sud-Renamed'
		print("load() persisted the edit to disk")

		assert sud.load({'Name': 'broken'}) is False
		assert sud.name == 'Sud-Renamed'
		print("load() rejected malformed data, left schedule untouched")

	print("All sud save/load checks passed")
