#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Gate Feedback — Perseveration tracking.

Detects when an agent violates the same pattern repeatedly within a
rolling 24-hour window, indicating the agent is stuck in a loop.
"""
from __future__ import annotations

import time

_violation_counts: dict = {}  # dict[str, dict[str, list[float]]]
_PERSEVERATION_WINDOW_HOURS = 24
_PERSEVERATION_THRESHOLD = 2  # >2 violations (i.e. 3+) without correction = perseveration


def _prune_old_violations(timestamps: list[float], now: float) -> list[float]:
    """Remove timestamps outside the rolling 24h window."""
    cutoff = now - _PERSEVERATION_WINDOW_HOURS * 3600
    return [t for t in timestamps if t >= cutoff]


def record_perseveration_violation(agent_id: str, pattern_id: str) -> None:
    """Record that agent_id violated pattern_id. Caller owns the corrective-action reset."""
    now = time.time()
    agent_map = _violation_counts.setdefault(agent_id, {})
    timestamps = agent_map.get(pattern_id, [])
    timestamps = _prune_old_violations(timestamps, now)
    timestamps.append(now)
    agent_map[pattern_id] = timestamps


def check_perseveration(agent_id: str, pattern_id: str) -> bool:
    """Return True if agent_id violated pattern_id >2 times in 24h (perseveration)."""
    now = time.time()
    agent_map = _violation_counts.get(agent_id, {})
    timestamps = _prune_old_violations(agent_map.get(pattern_id, []), now)
    if agent_id in _violation_counts:
        _violation_counts[agent_id][pattern_id] = timestamps
    return len(timestamps) > _PERSEVERATION_THRESHOLD


def reset_perseveration(agent_id: str, pattern_id: str) -> None:
    """Clear violation history after corrective action taken."""
    if agent_id in _violation_counts:
        _violation_counts[agent_id].pop(pattern_id, None)
