#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
pulse.daemons.neural.gate_feedback
===================================
Synaptic Gate-Feedback Engine — Brain V8 Phase 5 (D5)

Event-driven: called from autopilot loop.py on gate failures.
Captures exact failure context, generates temporary anti-patterns,
and produces corrective work orders for retry.

Closes the loop: failure -> learning -> informed retry.
Scheduler wiring handles decay only (not generation).

Public API
----------
record_gate_failure         — persist failure, return corrective dict
get_active_feedback         — non-expired entries for briefings
decay_old_feedback          — expire stale entries (scheduler)
check_perseveration         — detect stuck agents
record_perseveration_violation — log a violation
reset_perseveration         — clear after corrective action
"""
from __future__ import annotations

import logging
import os
import sys

if os.name == "nt" and __name__ == "__main__":
    sys.stdout.reconfigure(encoding="utf-8")
    sys.stderr.reconfigure(encoding="utf-8")

from pulse.daemons.neural.gate_feedback.core import (
    record_gate_failure,
    get_active_feedback,
    decay_old_feedback,
)
from pulse.daemons.neural.gate_feedback.perseveration import (
    record_perseveration_violation,
    check_perseveration,
    reset_perseveration,
    _violation_counts,
)

__all__ = [
    "record_gate_failure",
    "get_active_feedback",
    "decay_old_feedback",
    "record_perseveration_violation",
    "check_perseveration",
    "reset_perseveration",
]

# --- CLI Entry Point ---

if __name__ == "__main__":
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [D5] %(message)s",
        datefmt="%H:%M:%S",
    )
    if "--decay" in sys.argv:
        count = decay_old_feedback()
        print(f"[D5] Decayed {count} expired entries")
    elif "--status" in sys.argv:
        active = get_active_feedback(max_items=20)
        print(f"Active gate feedback entries: {len(active)}")
        for e in active:
            print(
                f"  [{e['failure_type']}] {e['task_title'][:60]} "
                f"— {e['anti_pattern'][:60]}"
            )
    elif "--once" in sys.argv:
        count = decay_old_feedback()
        print(f"[D5] Decay pass: {count} expired")
    else:
        print("[D5] Gate Feedback Engine is event-driven (called from autopilot).")
        print("     Use --decay to expire old entries, --status to view active.")
