"""Phase 3A: Prediction, DMN, Reflex, and Neural State coalitions.

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

import json
from pulse.core.paths import get_state_dir

def _calc_activation(relevance: float, salience: float, urgency: float, reliability: float) -> float:
    return relevance * min(1.0, salience / 7.0) * urgency * reliability

def get_prediction_coalition():
    """Prediction Oracle specialist coalition."""
    from pulse.brain.workspace.specialists import get_specialist, Coalition
    coal = get_specialist("prediction")
    alerts_file = get_state_dir() / "prediction_alerts.json"
    if not alerts_file.exists():
        coal.update([], 0.0)
        return coal
    try:
        with open(alerts_file, "r", encoding="utf-8") as f:
            data = json.load(f)
            alerts = data.get("active_alerts", [])
            if not alerts:
                coal.update([], 0.0)
                return coal
            alerts.sort(key=lambda x: x.get("confidence", 0), reverse=True)
            top = alerts[:3]
            act = _calc_activation(1.0, 5.0, 0.9, top[0].get("confidence", 0.5))
            coal.update(top, act)
            return coal
    except Exception:
        pass
    coal.update([], 0.0)
    return coal

def get_dmn_coalition():
    """DMN Ideation specialist coalition."""
    from pulse.brain.workspace.specialists import get_specialist, Coalition
    coal = get_specialist("dmn")
    proposals_file = get_state_dir() / "dmn" / "proposals.json"
    if not proposals_file.exists():
        coal.update([], 0.0)
        return coal
    try:
        with open(proposals_file, "r", encoding="utf-8") as f:
            data = json.load(f)
            if not data:
                coal.update([], 0.0)
                return coal
            latest = data[-3:]
            act = _calc_activation(0.6, 3.0, 0.3, 0.8)
            coal.update(latest, act)
            return coal
    except Exception:
        pass
    coal.update([], 0.0)
    return coal

def get_reflex_coalition():
    """Reflex Arc (mistakes) specialist coalition."""
    from pulse.brain.workspace.specialists import get_specialist, Coalition
    coal = get_specialist("reflex")
    try:
        from pulse.core.interoception import get_alerts
        alerts = get_alerts()
        error_alerts = [a for a in alerts if a["signal"] == "error_rate"]
        if error_alerts:
            act = _calc_activation(1.0, 7.0, 1.0, 1.0)
            coal.update(error_alerts, act)
            return coal
        coal.update([], 0.0)
        return coal
    except Exception:
        coal.update([], 0.0)
        return coal

def get_neural_state_coalition():
    """Neural State specialist coalition."""
    from pulse.brain.workspace.specialists import get_specialist, Coalition
    coal = get_specialist("neural_state")
    import pulse.core.interoception as interoception
    interoception.load_signals()
    if not interoception._signals:
        coal.update([], 0.0)
        return coal
    act = _calc_activation(0.8, 2.0, 0.4, 1.0)
    coal.update([{"type": "system_state", "metrics": interoception._signals}], act)
    return coal
