#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Working memory P36 extensions — Item 151: refresh rate tracking.

Kept separate from working_memory.py (300 lines) to respect the ceiling.
  - Item 151: Working memory refresh rate (eviction counter)
"""
import logging
from typing import Dict, Any

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

# ---------------------------------------------------------------------------
# Item 151: Working memory refresh rate (Memory)
# ---------------------------------------------------------------------------
_REFRESH_COUNT: int = 0
_HIGH_REFRESH_THRESHOLD: int = 50  # alert if more than 50 evictions observed

def increment_refresh_count(n: int = 1) -> int:
    """Increment the global eviction counter by n. Returns new total.

    Call this each time an item is evicted from working memory.
    Fails open (returns 0) on any error.
    """
    global _REFRESH_COUNT
    try:
        _REFRESH_COUNT += max(0, int(n))
        return _REFRESH_COUNT
    except Exception as exc:
        log.debug("increment_refresh_count failed: %s", exc)
        return 0


def get_refresh_count() -> int:
    """Return total eviction count since process start."""
    return _REFRESH_COUNT


def reset_refresh_count() -> None:
    """Reset eviction counter (e.g. per-session reset)."""
    global _REFRESH_COUNT
    _REFRESH_COUNT = 0


def get_refresh_rate_status() -> Dict[str, Any]:
    """Return refresh rate summary with volatility flag.

    Returns:
        {refresh_count, volatile, threshold, warning}
    """
    try:
        volatile = _REFRESH_COUNT >= _HIGH_REFRESH_THRESHOLD
        return {
            "refresh_count": _REFRESH_COUNT,
            "volatile": volatile,
            "threshold": _HIGH_REFRESH_THRESHOLD,
            "warning": (
                f"!! HIGH REFRESH RATE: {_REFRESH_COUNT} evictions — context is volatile"
                if volatile else None
            ),
        }
    except Exception as exc:
        log.debug("get_refresh_rate_status failed: %s", exc)
        return {
            "refresh_count": 0,
            "volatile": False,
            "threshold": _HIGH_REFRESH_THRESHOLD,
            "warning": None,
        }
