import json
import logging
import os

logger = logging.getLogger(__name__)


class PersistentList(list):
    def __init__(self, filename, encoder=None):
        super().__init__()
        self.filename = filename
        self.encoder = encoder
        self.load()

    def load(self):
        base_dir = os.environ.get("GRAMADDICT_ACCOUNTS_DIR", "accounts")
        path = f"{base_dir}/{self.filename}.json"
        if os.path.exists(path):
            try:
                with open(path, "r") as f:
                    data = json.load(f)
                    self.extend(data)
            except Exception as e:
                logger.error(f"Failed to load persistent list {self.filename}: {e}")

    def append(self, item):
        super().append(item)
        self.persist()

    def persist(self, directory=None):
        base_dir = os.environ.get("GRAMADDICT_ACCOUNTS_DIR", "accounts")
        folder = f"{base_dir}/{directory}" if directory else base_dir
        os.makedirs(folder, exist_ok=True)
        path = f"{folder}/{self.filename}.json"
        try:
            with open(path, "w") as f:
                json.dump(list(self), f, cls=self.encoder, indent=4)
        except Exception as e:
            logger.error(f"Failed to persist {self.filename}: {e}")
