#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Reward Integration: Brain learning updates triggered by reward signals.

Extracted from reward_signal.py (P46.7) to fix core→brain dependency inversion.
All brain-specific reward feedback lives here: STDP, Hebbian, metamemory, learned prompts.
"""
import logging
from datetime import datetime, timezone

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


def apply_learning_updates(success: bool, domain: str, agent: str,
                           rpe_delta: float, credits: dict,
                           retrieved_item_ids: list,
                           expected_success_rate: float):
    """Apply all brain learning updates from a reward signal.

    Called by reward_signal.record_task_outcome() after RPE + credit + propagation.
    Each integration is fail-open (try/except) — one failure doesn't block others.
    """
    # Source credibility feedback
    try:
        from pulse.brain.metacognition.metamemory_tracking import _record_source_outcome
        for _iid in list(credits.keys())[:10]:
            _src = str(_iid).split(":")[0] if ":" in str(_iid) else domain
            _record_source_outcome(_src, success)
        _record_source_outcome(domain, success)
    except Exception:
        pass

    # Event bus notification
    try:
        from pulse.core import event_bus
        event_bus.publish("reward.signal", "reward_signal", {
            "agent": agent, "success": success, "rpe_delta": rpe_delta})
    except Exception:
        pass

    # STDP + annealing
    _dt = datetime.now(timezone.utc)
    _min = (_dt.minute // 5) * 5
    _sid = _dt.strftime("%Y%m%d_%H") + f"_{_min:02d}"
    try:
        from pulse.brain.plasticity.stdp_annealing import apply_stdp_with_annealing
        apply_stdp_with_annealing(_sid, success, domain=domain)
    except Exception:
        try:
            from pulse.brain.plasticity.stdp import apply_stdp
            apply_stdp(_sid, success)
        except Exception:
            pass

    # Reward modulation
    try:
        from pulse.brain.plasticity.stdp import _apply_reward_modulation
        if success:
            _apply_reward_modulation(max(0.0, rpe_delta))
    except Exception:
        pass

    # Hebbian learning
    try:
        from pulse.brain.plasticity.hebbian_knowledge import apply_hebbian
        apply_hebbian(_sid, success)
    except Exception:
        pass

    # Learned prompt updates
    try:
        from pulse.brain.metacognition.learned_prompt import update_from_credits
        update_from_credits(domain, credits)
    except Exception:
        pass

    # Agent domain tracking
    try:
        from pulse.brain.metacognition.metamemory_tracking import _record_agent_domain
        _record_agent_domain(agent, domain, success)
    except Exception:
        pass

    # Meta-learning: knowledge type outcomes
    try:
        from pulse.brain.metacognition.metamemory import record_knowledge_type_outcome
        for _iid in retrieved_item_ids[:5]:
            record_knowledge_type_outcome("lesson", success)
    except Exception:
        pass

    # Calibration feedback
    try:
        from pulse.brain.metacognition.metamemory import _record_calibration
        _record_calibration(expected_success_rate, success)
    except Exception:
        pass
