"""
Rule Store — persistent (in-memory) store for the active memory policy.

Provides GET /policy/current and POST /policy/update semantics.
"""

import copy
import time
import threading
from typing import Dict, Any

DEFAULT_POLICY: Dict[str, Any] = {
    "policy_id": "default",
    "mode": "smart",
    "name": "Smart Memory Mode",
    "tagline": "We remember what works, not what doesn't.",
    "rules": {
        "store": ["success_task", "workflow", "preference", "decision"],
        "ignore": ["failed", "temporary", "noise"],
    },
    "user_description": "",
    "created_at": 0,
    "updated_at": 0,
}


class RuleStore:
    """Thread-safe in-memory store for the active memory policy."""

    def __init__(self):
        self._lock = threading.Lock()
        self._policy = copy.deepcopy(DEFAULT_POLICY)
        self._policy["created_at"] = int(time.time())
        self._policy["updated_at"] = int(time.time())
        self._history: list = []

    def get_current(self) -> Dict[str, Any]:
        with self._lock:
            return copy.deepcopy(self._policy)

    def update(self, patch: Dict[str, Any]) -> Dict[str, Any]:
        """Apply a partial update to the current policy."""
        with self._lock:
            self._history.append(copy.deepcopy(self._policy))
            if "rules" in patch:
                self._policy["rules"].update(patch["rules"])
            for k in ("mode", "name", "tagline", "user_description", "policy_id"):
                if k in patch:
                    self._policy[k] = patch[k]
            self._policy["updated_at"] = int(time.time())
            return copy.deepcopy(self._policy)

    def reset_to_default(self) -> Dict[str, Any]:
        with self._lock:
            self._history.append(copy.deepcopy(self._policy))
            self._policy = copy.deepcopy(DEFAULT_POLICY)
            self._policy["created_at"] = int(time.time())
            self._policy["updated_at"] = int(time.time())
            return copy.deepcopy(self._policy)

    def get_history(self) -> list:
        with self._lock:
            return list(self._history)
