import json
from .persistance_backend import PersistanceBackend


class InMemoryBackend(PersistanceBackend):
    """
    Persistence backend storing and returning dicts only (Option A).
    """

    def __init__(self, entity_class, storage=None):
        super().__init__(entity_class=entity_class)
        self._storage = storage if storage is not None else {}

    def save(self, entity_dict: dict):
        flexo_id = entity_dict["meta"]["flexo_id"]
        self._storage[flexo_id] = entity_dict

    def update(self, entity_dict: dict):
        self.save(entity_dict)

    def delete(self, flexo_id: str):
        self._storage.pop(flexo_id, None)

    def load(self, flexo_id: str):
        return self._storage.get(flexo_id)

    def load_all(self):
        return list(self._storage.values())

    def clear(self):
        self._storage.clear()

    # Optional file helpers still fine (dicts in/out)
    def save_to_file(self, path):
        with open(path, "w", encoding="utf-8") as f:
            json.dump(list(self._storage.values()), f, ensure_ascii=False, indent=2)

    def load_from_file(self, path):
        with open(path, "r", encoding="utf-8") as f:
            data = json.load(f)
        self._storage = {d["meta"]["flexo_id"]: d for d in data}
