"""Phase 3A: Working Memory, GWT broadcast, and Governance coalitions.

Split from specialists.py for Law 7 compliance.
Uses lazy imports to avoid circular dependency with specialists.py.
"""
from __future__ import annotations

def get_working_memory_coalition(agent: str):
    """Working Memory specialist coalition."""
    from pulse.brain.workspace.specialists import get_specialist, Coalition
    from pulse.brain.memory.working_memory import get_active_contexts
    coal = get_specialist("working_memory")
    active = get_active_contexts(agent)
    if not active:
        coal.update([], 0.0)
        return coal
    act = (1.0) * min(1.0, 4.0 / 7.0) * 0.7 * 1.0  # _calc_activation(0.9, 4.0, 0.7, 1.0)
    coal.update(active, act)
    return coal

def gwt_broadcast(broadcast_data: dict, winning_coalition=None) -> int:
    """Broadcast workspace content to all specialists; send reentrant to winner."""
    notified = 0
    try:
        from pulse.brain.workspace.specialists_oracle import (
            get_prediction_coalition, get_dmn_coalition, get_reflex_coalition,
        )
        coalitions = [get_prediction_coalition(), get_dmn_coalition(), get_reflex_coalition()]
        for coalition in coalitions:
            if hasattr(coalition, "receive_broadcast"):
                coalition.receive_broadcast(broadcast_data)
                notified += 1
    except Exception:
        pass
    try:
        if winning_coalition is not None and hasattr(winning_coalition, "receive_reentrant"):
            winning_coalition.receive_reentrant(broadcast_data)
    except Exception:
        pass
    return notified

def get_governance_coalition():
    """Governance specialist coalition (always-admit)."""
    from pulse.brain.workspace.specialists import get_specialist, Coalition
    coal = get_specialist("governance")
    coal.update([], 0.0)
    return coal
