from .storage import get_storage

class pvar:
    def __init__(self, name, initial=None):
        if not isinstance(name, str) or not name:
            raise ValueError("name must be a non-empty string.")

        if not self._is_primitive(initial):
            raise TypeError("pvar must be a primitive (int, float, bool, str, None)")

        self._storage = get_storage()
        self._name = name

        name_id = self._storage.get_named(name, "var")
        if name_id is None:
            self.id = self._storage.generate_id()
            self._value = initial
            self._persist()
            self._storage.set_named(name, self.id, "var")
        else:
            self.id = name_id
            loaded = self._storage.get(name_id)
            if loaded is None:
                self._value = initial
                self._persist()
            else:
                object_type, data = loaded
                if object_type != "var":
                    raise TypeError("Stored object is not a pvar")
                self._value = data
    @staticmethod
    def _is_primitive(value):
        return value is None or isinstance(value, (int, float, bool, str))
    @property
    def value(self):
        return self._value
    
    @value.setter
    def value(self, new_value):
        if not self._is_primitive(new_value):
            raise TypeError("value must be a primitive (int, float, bool, str, None)")
        self._value = new_value
        self._persist()
    
    def get(self):
        return self._value
    
    def set(self, new_value):
        self.value = new_value

    def __repr__(self):
        return repr(self._value)
    
    def _persist(self):
        self._storage.save(self.id, "var", self._value)
    