import json
import sys
from pathlib import Path
from ..ImporterException import LoadError


# Get the filesystem encoding for the current system
ENCODING = sys.getfilesystemencoding()


class DataCache:
    """
    A class for managing package data caching using JSON files.

    This class provides functionality to create, read, update, and clear
    a cache file storing package information in JSON format.
    """

    # Define class slots to optimize memory usage
    __slots__ = "cache_file"

    def __init__(
        self, pathdir: str = ".pkgs_cache", pathfile: str = "cache-pkgs.json"
    ) -> str:
        """
        Initialize the DataCache instance.

        Returns:
            str: This is likely a documentation error as the method doesn't return a string.
        """
        # Define cache directory path
        CACHE_DIR = Path(pathdir)
        # Create cache directory if it doesn't exist
        if not CACHE_DIR.exists():
            CACHE_DIR.mkdir()

        self.cache_file = Path(pathdir) / Path(pathfile)  # Define cache file path

    def init(self):
        """
        Prepare the cache file for use.

        This method:
        1. Checks if the cache file exists
        2. Reads existing content if available
        3. Initializes with empty list if file is empty
        4. Writes the content back to ensure proper file format
        """
        cache_path = Path(self.cache_file)

        content = []  # Initialize empty content
        if cache_path.exists():
            # Read existing content from cache file
            with open(cache_path, "r", encoding=ENCODING) as load:
                content = load.read().strip()
                # Handle empty file case
                if not content:
                    content = []
                elif content == "[" or content == "]":
                    content = []
                else:
                    # Parse JSON content
                    content = json.loads(content)
        # Write content back to file (ensures proper formatting)
        with open(cache_path, "w", encoding=ENCODING) as storage:
            json.dump(content, storage, ensure_ascii=False)

    def cache(self, listofdata: list = None):
        """
        Cache the current package list to the file.

        This method writes the current data list (self.listofdata)
        to the cache file in JSON format.
        """
        with open(self.cache_file, "w", encoding=ENCODING) as storage:
            json.dump(listofdata, storage, ensure_ascii=False)

    def exists(self):
        return self.cache_file.exists()

    def clear(self):
        """
        Clear the cache file content.

        This method truncates the cache file, effectively removing
        all cached data while keeping the file itself.
        """
        open(self.cache_file, "w").close()

    def load(self):
        """
        Load and return data from the cache file.

        Returns:
            list: The cached data as a Python list.

        Raises:
            LoadError: If the cache file contains invalid JSON format.
        """
        try:
            # Attempt to read and parse the cache file
            with open(self.cache_file, "r") as load:
                return json.load(load)
        except json.decoder.JSONDecodeError:
            # Handle malformed JSON data
            raise LoadError(f"failed to load cache file (InvalidFormat)") from None
