import os
import orjson
from typing import Any
from pathlib import Path

def load_json( filepath : str | Path ) -> None :
	with open(filepath, 'rb') as f:
		return orjson.loads(f.read())

def save_json( data : dict[str,Any], filepath : str | Path ) -> None :
	temp_path = f"{filepath}.tmp"
	try:
		with open(temp_path, 'wb') as f:  # Note: 'wb' - orjson.dumps returns bytes
			f.write(orjson.dumps(data, option=orjson.OPT_INDENT_2 | orjson.OPT_SERIALIZE_NUMPY ))
			f.flush()
			os.fsync(f.fileno())
		os.replace(temp_path, filepath)
	
	except Exception as e:
		print(f"An error occurred while saving the file: {e}")
		if os.path.exists(temp_path):
			try:
				os.remove(temp_path)
			except OSError as cleanup_error:
				print(f"Failed to clean up temporary file '{temp_path}': {cleanup_error}")

def save_json_if_changed( data : dict[str,Any], filepath : str | Path ) -> None :
	if os.path.exists( filepath ):
		existing = load_json( filepath )
		existing_bytes = orjson.dumps(existing)
		current_bytes = orjson.dumps(data)
		if existing_bytes == current_bytes:
			return
	safe_save( data, filepath )
