"""Cache Manager - Handle application caching""" import json import time import shutil from pathlib import Path from typing import Any, Optional, Dict from dataclasses import dataclass, field @dataclass class CacheEntry: """Single cache entry""" key: str value: Any created_at: float = field(default_factory=time.time) expires_at: Optional[float] = None hits: int = 0 def is_expired(self) -> bool: """Check if entry has expired""" if self.expires_at is None: return False return time.time() > self.expires_at class CacheManager: """Manage application cache""" def __init__(self, cache_dir: Optional[str] = None, default_ttl: int = 3600): if cache_dir: self.cache_dir = Path(cache_dir) else: self.cache_dir = Path.home() / ".burme_coder" / "cache" self.cache_dir.mkdir(parents=True, exist_ok=True) self.default_ttl = default_ttl self.memory_cache: Dict[str, CacheEntry] = {} def get(self, key: str, use_memory: bool = True) -> Optional[Any]: """Get value from cache""" if use_memory and key in self.memory_cache: entry = self.memory_cache[key] if not entry.is_expired(): entry.hits += 1 return entry.value else: del self.memory_cache[key] cache_file = self._get_cache_file(key) if cache_file and cache_file.exists(): try: data = json.loads(cache_file.read_text(encoding="utf-8")) entry = CacheEntry( key=key, value=data["value"], created_at=data.get("created_at", time.time()), expires_at=data.get("expires_at"), ) if not entry.is_expired(): return entry.value else: cache_file.unlink() except (json.JSONDecodeError, KeyError): pass return None def set( self, key: str, value: Any, ttl: Optional[int] = None, use_memory: bool = True ): """Set value in cache""" ttl = ttl if ttl is not None else self.default_ttl expires_at = time.time() + ttl if ttl > 0 else None if use_memory: self.memory_cache[key] = CacheEntry(key=key, value=value, expires_at=expires_at) cache_file = self._get_cache_file(key) if cache_file: cache_data = { "key": key, "value": value, "created_at": time.time(), "expires_at": expires_at, } cache_file.write_text(json.dumps(cache_data), encoding="utf-8") def delete(self, key: str): """Delete cache entry""" if key in self.memory_cache: del self.memory_cache[key] cache_file = self._get_cache_file(key) if cache_file and cache_file.exists(): cache_file.unlink() def clear(self, pattern: Optional[str] = None): """Clear cache entries""" if pattern: for cache_file in self.cache_dir.glob(f"{pattern}*"): cache_file.unlink() else: for cache_file in self.cache_dir.glob("*.json"): cache_file.unlink() self.memory_cache.clear() def cleanup_expired(self): """Remove all expired entries""" expired_keys = [k for k, v in self.memory_cache.items() if v.is_expired()] for key in expired_keys: del self.memory_cache[key] for cache_file in self.cache_dir.glob("*.json"): try: data = json.loads(cache_file.read_text(encoding="utf-8")) if data.get("expires_at") and time.time() > data["expires_at"]: cache_file.unlink() except (json.JSONDecodeError, KeyError): pass def get_stats(self) -> Dict: """Get cache statistics""" total_hits = sum(e.hits for e in self.memory_cache.values()) entries_count = len(self.memory_cache) disk_files = len(list(self.cache_dir.glob("*.json"))) return { "memory_entries": entries_count, "disk_files": disk_files, "total_hits": total_hits, "cache_dir": str(self.cache_dir), } def _get_cache_file(self, key: str) -> Optional[Path]: """Get cache file path for key""" safe_key = "".join(c if c.isalnum() or c in "-_" else "_" for c in key) if len(safe_key) > 50: import hashlib safe_key = hashlib.md5(key.encode()).hexdigest() return self.cache_dir / f"{safe_key}.json" def clear_all(self): """Clear all caches including memory""" self.memory_cache.clear() if self.cache_dir.exists(): shutil.rmtree(self.cache_dir) self.cache_dir.mkdir(parents=True, exist_ok=True)