#!/usr/bin/env python3
"""Cache module for Alfred Hook Lookup workflow."""

import pickle
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Optional

CACHE_TTL = float("inf")
CACHE_DIR = Path(__file__).parent / ".cache"


@dataclass
class CacheEntry:
    """Represents a cached entry with timestamp."""

    data: Any
    timestamp: float


class HookCache:
    """Manages persistent caching for hook lookups."""

    def __init__(
        self,
    ):
        """Initialize the cache."""

        self.cache_file = CACHE_DIR / "hook_cache.pkl"
        self._cache: Dict[str, CacheEntry] = {}
        self._loaded = False

    def _ensure_loaded(self) -> None:
        """Ensure cache is loaded from disk."""
        if not self._loaded:
            self._load()
            self._loaded = True

    def _load(self) -> None:
        """Load cache from disk if it exists."""
        if self.cache_file.exists():
            try:
                with open(self.cache_file, "rb") as f:
                    self._cache = pickle.load(f)
            except Exception:
                # If cache is corrupted, start fresh
                self._cache = {}
        else:
            self._cache = {}

    def _save(self) -> None:
        """Save cache to disk."""
        CACHE_DIR.mkdir(parents=True, exist_ok=True)
        with open(self.cache_file, "wb") as f:
            pickle.dump(self._cache, f)

    def get(self, key: str) -> Optional[Any]:
        self._ensure_loaded()

        if key not in self._cache:
            return None

        entry = self._cache[key]

        # Check if expired
        if time.time() - entry.timestamp > CACHE_TTL:
            # Remove expired entry
            del self._cache[key]
            self._save()
            return None

        return entry.data

    def set(self, key: str, value: Any) -> None:
        self._ensure_loaded()

        self._cache[key] = CacheEntry(data=value, timestamp=time.time())
        self._save()

    def clear(self) -> None:
        self._cache = {}
        self._save()

    def remove(self, key: str) -> bool:
        self._ensure_loaded()

        if key in self._cache:
            del self._cache[key]
            self._save()
            return True
        return False
