"""Circuit breaker for the Oracle prediction daemon.

QR14: Flagged by ALL 25 expert panels — Oracle enters recursive seizure loop
without this guard. Prevents >5 predictions in 10 minutes, then 30-min cooldown.
"""
import logging
import time

log = logging.getLogger("pulse.daemons.neural.prediction_circuit_breaker")

CIRCUIT_BREAKER_WINDOW = 600       # 10 minutes
CIRCUIT_BREAKER_MAX = 5            # max predictions in window
CIRCUIT_BREAKER_COOLDOWN = 1800    # 30 min cooldown after trip
_recent_prediction_times: list[float] = []
_circuit_tripped_until: float = 0.0


def circuit_breaker_check() -> bool:
    """Return True if the circuit breaker is tripped (too many recent predictions)."""
    global _circuit_tripped_until
    now = time.time()
    if now < _circuit_tripped_until:
        return True  # still in cooldown
    # Prune old timestamps outside the window
    cutoff = now - CIRCUIT_BREAKER_WINDOW
    _recent_prediction_times[:] = [t for t in _recent_prediction_times if t > cutoff]
    if len(_recent_prediction_times) >= CIRCUIT_BREAKER_MAX:
        _circuit_tripped_until = now + CIRCUIT_BREAKER_COOLDOWN
        log.warning("Oracle circuit breaker TRIPPED: %d predictions in %ds, cooling down %ds",
                     len(_recent_prediction_times), CIRCUIT_BREAKER_WINDOW, CIRCUIT_BREAKER_COOLDOWN)
        return True
    return False


def record_prediction():
    """Record a prediction timestamp for circuit breaker tracking."""
    _recent_prediction_times.append(time.time())
