import os
from platformdirs import user_cache_dir
import pickle
import logging

class Cache:
    def __init__(self, project_name: str, cache_dir: str = None):
        self.project_name = project_name
        self.cache_dir = cache_dir or user_cache_dir("vskache", "vsk")
        self.project_cache_dir = os.path.join(self.cache_dir, project_name)

    def validate_cache(self):
        """Check if the cache directory exists and is writable."""
        if not os.path.exists(self.cache_dir):
            os.makedirs(self.cache_dir)
        if not os.path.exists(self.project_cache_dir):
            os.makedirs(self.project_cache_dir)
        if not os.access(self.project_cache_dir, os.W_OK):
            raise PermissionError(f"Cache directory '{self.cache_dir}' is not writable.")

    def clear(self):
        """Clear the cache for the project."""
        self.validate_cache()
        if os.path.exists(self.project_cache_dir):
            for filename in os.listdir(self.project_cache_dir):
                file_path = os.path.join(self.project_cache_dir, filename)
                try:
                    os.remove(file_path)
                    logging.info(f"Removed cache file: {file_path}")
                except Exception as e:
                    logging.error(f"Error removing cache file {file_path}: {e}")
        else:
            logging.warning(f"Cache directory does not exist: {self.project_cache_dir}")

    def save(self, key: str, value: any):
        """Save a value to the cache with the given key."""
        self.validate_cache()
        file_path = os.path.join(self.project_cache_dir, f"{key}.pkl")
        if os.path.exists(file_path):
            logging.warning(f"Overwriting existing cache file: {file_path}")
        with open(file_path, 'wb') as f:
            pickle.dump(value, f)
            logging.info(f"Saved cache for key: {key} at {file_path}")

    def load(self, key: str):
        """Load a value from the cache with the given key."""
        self.validate_cache()
        file_path = os.path.join(self.project_cache_dir, f"{key}.pkl")
        if not os.path.exists(file_path):
            logging.warning(f"Cache file not found: {file_path}")
            return None 
        with open(file_path, 'rb') as f:
            value = pickle.load(f)
            logging.warning(f"Loading cache for key: {key} from {file_path}")
            return value
