o
    jEiH                     @   s6   d dl Z d dlZd dlmZ eeZG dd dZdS )    N)	getLoggerc                   @   s:   e Zd ZdZdddZdd Zdd Zd	d
 Zdd ZdS )XaiCachez^
    A simple persistent JSON-based cache for XAI API responses to avoid redundant calls.
    xai_cache.jsonc                 C   s   || _ |  | _d S )N)
cache_path_load_cachecache)selfr    r	   0/var/www/agentarbitrage/keepa_deals/xai_cache.py__init__   s   zXaiCache.__init__c              	   C   s   t j| jstd i S z)t| jd}t|}W d   n1 s%w   Y  tdt	| d |W S  t
tjfyO   td| j d i  Y S w )z!Loads the cache from a JSON file.z7XAI cache file not found. Starting with an empty cache.rNzSuccessfully loaded z items from XAI cache.zCould not read or parse 'z '. Starting with an empty cache.)ospathexistsr   loggerinfoopenjsonloadlenIOErrorJSONDecodeErrorwarning)r   fr   r	   r	   r
   r      s   
zXaiCache._load_cachec              
   C   s   z$t | jd}tj| j|dd W d   W dS 1 sw   Y  W dS  tyC } ztd| j d|  W Y d}~dS d}~ww )z+Saves the in-memory cache to the JSON file.w   )indentNzCould not save XAI cache to 'z': )r   r   r   dumpr   r   r   error)r   r   er	   r	   r
   _save_cache   s   &&zXaiCache._save_cachec                 C   s<   | j |}|rtd| d |S td| d |S )zu
        Retrieves a value from the cache.
        Returns the cached value or None if the key is not found.
        zXAI Cache HIT for key: ''zXAI Cache MISS for key: ')r   getr   debug)r   keyresultr	   r	   r
   r"   %   s   zXaiCache.getc                 C   s(   t d| d || j|< |   dS )zJ
        Adds a key-value pair to the cache and saves it to disk.
        zXAI Cache SET for key: 'r!   N)r   r#   r   r    )r   r$   valuer	   r	   r
   set1   s   
zXaiCache.setN)r   )	__name__
__module____qualname____doc__r   r   r    r"   r'   r	   r	   r	   r
   r      s    
r   )r   r   loggingr   r(   r   r   r	   r	   r	   r
   <module>   s
    