#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Reconsolidation stability metric — Item 164.

  - Item 164: Memory reconsolidation stability metric (Monitoring)

Track how many items are reconsolidated per hour. High rate = unstable memory.
"""
import logging
import time
from collections import deque
from typing import Dict, Any

log = logging.getLogger("pulse.brain.reconsolidation_stability")

# Rolling window of reconsolidation timestamps (epoch seconds)
_RECON_TIMESTAMPS: deque = deque(maxlen=1000)
_HIGH_RATE_THRESHOLD = 30   # items/hour that triggers instability warning


def record_reconsolidation_event() -> None:
    """Record a single reconsolidation event. Call when mark_labile() fires.

    Fails open silently.
    """
    try:
        _RECON_TIMESTAMPS.append(time.time())
    except Exception:
        pass


def get_reconsolidation_rate() -> Dict[str, Any]:
    """Compute reconsolidation rate per hour over the last 60 minutes.

    Returns:
        {events_last_hour, rate_per_hour, unstable, warning}
    Fails open (returns 0 rate) on any error.
    """
    result: Dict[str, Any] = {
        "events_last_hour": 0,
        "rate_per_hour": 0.0,
        "unstable": False,
        "warning": None,
    }
    try:
        now = time.time()
        cutoff = now - 3600  # last 60 minutes
        events = sum(1 for ts in _RECON_TIMESTAMPS if ts >= cutoff)
        unstable = events >= _HIGH_RATE_THRESHOLD
        warning = None
        if unstable:
            warning = (
                f"!! UNSTABLE MEMORY: {events} reconsolidations in last hour "
                f"(threshold={_HIGH_RATE_THRESHOLD}). Memory is highly volatile."
            )
        result.update({
            "events_last_hour": events,
            "rate_per_hour": float(events),
            "unstable": unstable,
            "warning": warning,
        })
    except Exception as exc:
        log.debug("get_reconsolidation_rate failed: %s", exc)
    return result
