"""P15 Neuroscience Refinements: Source Inspection Tests (Items 56-60)."""

ROOT = "C:/Users/ovall/Documents/projects/babel_bot/PULSE"
WM_PATH    = ROOT + "/pulse/brain/working_memory.py"
BRIEF_PATH = ROOT + "/pulse/brain/brain_query/briefing.py"
STDP_PATH  = ROOT + "/pulse/brain/stdp.py"
SPEC_PATH  = ROOT + "/pulse/brain/specialists.py"
HEBB_PATH  = ROOT + "/pulse/brain/hebbian_knowledge.py"


def _src(path):
    with open(path, encoding="utf-8") as f:
        return f.read()


def _lines(path):
    return _src(path).count("\n") + 1


def _block(src, marker, end="\ndef "):
    idx = src.find(marker)
    if idx == -1: return ""
    nxt = src.find(end, idx + 1)
    return src[idx:nxt] if nxt != -1 else src[idx:]


def _mblock(src, marker, end="\n    def "):
    idx = src.find(marker)
    if idx == -1: return ""
    nxt = src.find(end, idx + 1)
    return src[idx:nxt] if nxt != -1 else src[idx:idx + 400]


# ===== Item 56: Pre-conscious buffer =====

class TestItem56PreConsciousBuffer:

    def test_buffer_constant_exists(self):
        assert "_PRECONSCIOUS_BUFFER" in _src(WM_PATH)

    def test_buffer_is_list(self):
        src = _src(WM_PATH)
        assert "_PRECONSCIOUS_BUFFER: list = []" in src or "_PRECONSCIOUS_BUFFER = []" in src

    def test_salience_range_bounds(self):
        src = _src(WM_PATH)
        assert "0.3" in src and "0.6" in src

    def test_ttl_300_seconds(self):
        assert "300" in _src(WM_PATH)

    def test_buffer_used_in_evict(self):
        src = _src(WM_PATH)
        block = _block(src, "def _evict(session")
        assert "_PRECONSCIOUS_BUFFER" in block

    def test_promotion_above_0_6(self):
        src = _src(WM_PATH)
        block = _block(src, "def _evict(session")
        assert "0.6" in block and "salience" in block

    def test_buffer_size_cap(self):
        assert "-20" in _src(WM_PATH)

    def test_buf_ts_key_present(self):
        assert "_buf_ts" in _src(WM_PATH)


# ===== Item 57: Failed ignition =====

class TestItem57FailedIgnition:

    def test_failed_ignition_label(self):
        assert "FAILED IGNITION" in _src(BRIEF_PATH)

    def test_ignition_in_zero_results_block(self):
        src = _src(BRIEF_PATH)
        idx = src.find("if total == 0:")
        assert idx != -1
        assert "FAILED IGNITION" in src[idx:idx + 600]

    def test_broader_query_first_two_words(self):
        assert "split()[:2]" in _src(BRIEF_PATH)

    def test_brain_search_retry_import(self):
        assert "brain_search" in _src(BRIEF_PATH)

    def test_avg_conf_low_threshold(self):
        assert "avg_conf < 0.3" in _src(BRIEF_PATH)

    def test_fail_open_wrap(self):
        src = _src(BRIEF_PATH)
        idx = src.find("FAILED IGNITION")
        zone = src[max(0, idx - 300):idx + 300]
        assert "try:" in zone and "except" in zone


# ===== Item 58: Hebb window 300s =====

class TestItem58HebbWindow:

    def test_hebb_window_constant(self):
        assert "_HEBB_WINDOW" in _src(STDP_PATH)

    def test_hebb_window_is_300(self):
        assert "_HEBB_WINDOW = 300" in _src(STDP_PATH)

    def test_hebb_window_5min_comment(self):
        src = _src(STDP_PATH)
        idx = src.find("_HEBB_WINDOW")
        line = src[idx:idx + 120]
        assert "5" in line or "minute" in line.lower()

    def test_hebbian_5min_bucket(self):
        src = _src(HEBB_PATH)
        assert "// 5" in src or "_min" in src

    def test_hebbian_minute_bucketing(self):
        src = _src(HEBB_PATH)
        assert "// 5" in src or "_min58" in src or "_min" in src

    def test_temporal_window_s_still_120(self):
        assert "TEMPORAL_WINDOW_S = 120" in _src(STDP_PATH)


# ===== Item 59: GWT broadcast to all specialists =====

class TestItem59GWTBroadcast:

    def test_receive_broadcast_method(self):
        assert "def receive_broadcast" in _src(SPEC_PATH)

    def test_gwt_broadcast_function(self):
        assert "def gwt_broadcast" in _src(SPEC_PATH)

    def test_broadcast_iterates_coalitions(self):
        src = _src(SPEC_PATH)
        block = _block(src, "def gwt_broadcast")
        assert "receive_broadcast" in block and ("for " in block or "coalitions" in block)

    def test_broadcast_references_multiple_getters(self):
        src = _src(SPEC_PATH)
        block = _block(src, "def gwt_broadcast")
        refs = sum(1 for n in [
            "get_prediction_coalition", "get_dmn_coalition",
            "get_reflex_coalition", "get_memory_coalition",
        ] if n in block)
        assert refs >= 2

    def test_broadcast_fail_open(self):
        src = _src(SPEC_PATH)
        block = _block(src, "def gwt_broadcast")
        assert "try:" in block and "except" in block

    def test_receive_broadcast_access_count(self):
        src = _src(SPEC_PATH)
        block = _mblock(src, "def receive_broadcast")
        assert "access_count" in block


# ===== Item 60: Reentrant signal =====

class TestItem60ReentrantSignal:

    def test_receive_reentrant_method(self):
        assert "def receive_reentrant" in _src(SPEC_PATH)

    def test_reentrant_access_count(self):
        src = _src(SPEC_PATH)
        block = _mblock(src, "def receive_reentrant")
        assert "access_count" in block

    def test_reentrant_last_broadcast_item(self):
        src = _src(SPEC_PATH)
        block = _mblock(src, "def receive_reentrant")
        assert "last_broadcast_item" in block

    def test_reentrant_fail_open(self):
        src = _src(SPEC_PATH)
        block = _mblock(src, "def receive_reentrant")
        assert "try:" in block and "except" in block

    def test_gwt_calls_reentrant(self):
        src = _src(SPEC_PATH)
        block = _block(src, "def gwt_broadcast")
        assert "receive_reentrant" in block

    def test_gwt_winning_coalition_param(self):
        src = _src(SPEC_PATH)
        idx = src.find("def gwt_broadcast")
        line_end = src.find("\n", idx)
        sig_line = src[idx:line_end]
        assert "winning_coalition" in sig_line

    def test_coalition_init_access_count(self):
        src = _src(SPEC_PATH)
        block = _mblock(src, "def __init__(self, source")
        assert "access_count" in block

    def test_coalition_init_last_broadcast_item(self):
        src = _src(SPEC_PATH)
        block = _mblock(src, "def __init__(self, source")
        assert "last_broadcast_item" in block


# ===== File size limits =====

class TestFileLimits:

    def test_working_memory_under_300(self):
        assert _lines(WM_PATH) <= 300

    def test_briefing_under_300(self):
        assert _lines(BRIEF_PATH) <= 300

    def test_stdp_under_300(self):
        assert _lines(STDP_PATH) <= 300

    def test_specialists_under_300(self):
        assert _lines(SPEC_PATH) <= 300

    def test_hebbian_knowledge_under_300(self):
        assert _lines(HEBB_PATH) <= 300
