#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Reward regulation extensions — Item 167.

  - Item 167: Emotional regulation feedback (Reward)

Log how often emotional regulation cap fires. Alert if it fires frequently
(brain is too emotional).
"""
import logging
from typing import Dict, Any

log = logging.getLogger("pulse.core.reward_regulation")

_REGULATION_COUNT: int = 0
_REGULATION_FIRE_THRESHOLD = 20   # alert if regulation fires this many times


def increment_regulation_count(n: int = 1) -> int:
    """Record that the emotional regulation cap fired n times.

    Call this each time the salience cap (> 6.0 diminishing returns)
    fires in propagate_reward().
    Fails open (returns 0) on any error.
    """
    global _REGULATION_COUNT
    try:
        _REGULATION_COUNT += max(0, int(n))
        return _REGULATION_COUNT
    except Exception as exc:
        log.debug("increment_regulation_count failed: %s", exc)
        return 0


def get_regulation_count() -> int:
    """Return total regulation cap fires since process start."""
    return _REGULATION_COUNT


def reset_regulation_count() -> None:
    """Reset counter (e.g. per-session)."""
    global _REGULATION_COUNT
    _REGULATION_COUNT = 0


def get_regulation_status() -> Dict[str, Any]:
    """Return emotional regulation status with alert if firing frequently.

    Returns:
        {regulation_count, threshold, over_emotional, warning}
    """
    try:
        over = _REGULATION_COUNT >= _REGULATION_FIRE_THRESHOLD
        return {
            "regulation_count": _REGULATION_COUNT,
            "threshold": _REGULATION_FIRE_THRESHOLD,
            "over_emotional": over,
            "warning": (
                f"!! OVER-EMOTIONAL BRAIN: Regulation cap fired {_REGULATION_COUNT} times "
                f"(threshold={_REGULATION_FIRE_THRESHOLD}). "
                "Brain is amplifying salience too aggressively."
                if over else None
            ),
        }
    except Exception as exc:
        log.debug("get_regulation_status failed: %s", exc)
        return {
            "regulation_count": 0,
            "threshold": _REGULATION_FIRE_THRESHOLD,
            "over_emotional": False,
            "warning": None,
        }
