"""P18 Neuroscience Refinements: Source Inspection Tests (Items 71-75)."""

ROOT = "C:/Users/ovall/Documents/projects/babel_bot/PULSE"
FS_PATH  = ROOT + "/pulse/brain/fact_store.py"
SM_PATH  = ROOT + "/pulse/daemons/consolidation/stages/stage_maintenance.py"
BR_PATH  = ROOT + "/pulse/brain/brain_query/briefing.py"
RC_PATH  = ROOT + "/pulse/brain/reconsolidation.py"
TC_PATH  = ROOT + "/pulse/tasks/task_claiming.py"


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


def _lines(path):
    return len(_src(path).splitlines())


# ===== Item 71: Episodic-to-semantic graduation =====

class TestItem71EpisodicGraduation:

    def test_function_exists(self):
        assert "_check_graduation" in _src(FS_PATH)

    def test_checks_episodic_type(self):
        src = _src(FS_PATH)
        assert '"episodic"' in src or "'episodic'" in src

    def test_checks_access_count_threshold(self):
        src = _src(FS_PATH)
        assert "access_count" in src
        assert ">= 5" in src

    def test_checks_confidence_threshold(self):
        src = _src(FS_PATH)
        assert "0.7" in src
        assert "confidence" in src

    def test_updates_to_semantic(self):
        src = _src(FS_PATH)
        assert "type = 'semantic'" in src or 'type = "semantic"' in src

    def test_fail_open_try_except(self):
        src = _src(FS_PATH)
        # _check_graduation must have its own try/except
        grad_idx = src.index("def _check_graduation")
        next_def = src.index("\ndef ", grad_idx + 1)
        func_body = src[grad_idx:next_def]
        assert "try:" in func_body
        assert "except Exception:" in func_body

    def test_returns_bool(self):
        src = _src(FS_PATH)
        assert "return True" in src
        assert "return False" in src

    def test_uses_brain_db(self):
        src = _src(FS_PATH)
        assert "brain_db" in src

    def test_file_under_300_lines(self):
        assert _lines(FS_PATH) < 300


# ===== Item 72: Proactive interference recency bonus =====

class TestItem72RecencyBonus:

    def test_function_exists(self):
        assert "stage_recency_bonus" in _src(SM_PATH)

    def test_boosts_recent_items(self):
        src = _src(SM_PATH)
        assert "confidence + 0.05" in src or "confidence + 0.05" in src

    def test_confidence_ceiling(self):
        src = _src(SM_PATH)
        assert "MIN(1.0" in src or "min(1.0" in src

    def test_uses_one_day_cutoff(self):
        src = _src(SM_PATH)
        assert "timedelta(days=1)" in src or "days=1" in src

    def test_applies_to_all_three_tables(self):
        src = _src(SM_PATH)
        assert '"lessons"' in src or "'lessons'" in src
        assert '"failures"' in src or "'failures'" in src
        assert '"patterns"' in src or "'patterns'" in src

    def test_fail_open(self):
        src = _src(SM_PATH)
        # stage_recency_bonus must have try/except
        bonus_idx = src.index("def stage_recency_bonus")
        next_def = src.index("\ndef ", bonus_idx + 1)
        func_body = src[bonus_idx:next_def]
        assert "try:" in func_body
        assert "except Exception" in func_body

    def test_returns_status_ok(self):
        src = _src(SM_PATH)
        bonus_idx = src.index("def stage_recency_bonus")
        next_def = src.index("\ndef ", bonus_idx + 1)
        func_body = src[bonus_idx:next_def]
        assert '"status": "ok"' in func_body or '"status"' in func_body

    def test_file_under_300_lines(self):
        assert _lines(SM_PATH) < 300


# ===== Item 73: Cognitive load-based response format =====

class TestItem73CognitiveLoadFormat:

    def test_render_items_function_exists(self):
        assert "_render_items" in _src(BR_PATH)

    def test_s1_terse_format(self):
        src = _src(BR_PATH)
        assert "S1" in src
        assert "[:80]" in src

    def test_s2_detailed_format(self):
        src = _src(BR_PATH)
        assert "S2" in src
        assert "conf=" in src
        assert "src=" in src

    def test_s2_uses_120_chars(self):
        src = _src(BR_PATH)
        assert "[:120]" in src

    def test_format_conditional_on_system_mode(self):
        src = _src(BR_PATH)
        assert "_system_mode" in src
        # Should branch on S1 vs S2
        assert '"S1"' in src or "'S1'" in src

    def test_fail_open_in_render_items(self):
        src = _src(BR_PATH)
        render_idx = src.index("def _render_items")
        # _render_items is nested; capture 600 chars for its full body
        # check try/except somewhere after _render_items
        func_body = src[render_idx:render_idx + 600]
        assert "try:" in func_body
        assert "except Exception" in func_body

    def test_file_under_300_lines(self):
        assert _lines(BR_PATH) < 300


# ===== Item 74: Superseded chain resolution =====

class TestItem74SupersededChain:

    def test_function_exists(self):
        assert "_resolve_superseded_chain" in _src(RC_PATH)

    def test_max_depth_parameter(self):
        src = _src(RC_PATH)
        assert "max_depth" in src
        assert "max_depth: int = 5" in src or "max_depth=5" in src

    def test_follows_superseded_by_field(self):
        src = _src(RC_PATH)
        assert "superseded_by" in src

    def test_loop_up_to_max_depth(self):
        src = _src(RC_PATH)
        chain_idx = src.index("def _resolve_superseded_chain")
        next_def = src.index("\ndef ", chain_idx + 1)
        func_body = src[chain_idx:next_def]
        assert "range(max_depth)" in func_body

    def test_returns_item_id_on_failure(self):
        src = _src(RC_PATH)
        chain_idx = src.index("def _resolve_superseded_chain")
        next_def = src.index("\ndef ", chain_idx + 1)
        func_body = src[chain_idx:next_def]
        assert "return item_id" in func_body

    def test_fail_open_try_except(self):
        src = _src(RC_PATH)
        chain_idx = src.index("def _resolve_superseded_chain")
        next_def = src.index("\ndef ", chain_idx + 1)
        func_body = src[chain_idx:next_def]
        assert "try:" in func_body
        assert "except Exception" in func_body

    def test_validates_table_against_whitelist(self):
        src = _src(RC_PATH)
        chain_idx = src.index("def _resolve_superseded_chain")
        next_def = src.index("\ndef ", chain_idx + 1)
        func_body = src[chain_idx:next_def]
        assert "_VALID_TABLES" in func_body

    def test_queries_validity_superseded(self):
        src = _src(RC_PATH)
        assert "validity = 'superseded'" in src or 'validity = "superseded"' in src

    def test_file_under_300_lines(self):
        assert _lines(RC_PATH) < 300


# ===== Item 75: Near-miss pattern extraction =====

class TestItem75NearMissPattern:

    def test_near_miss_check_present(self):
        src = _src(TC_PATH)
        assert "near_miss" in src

    def test_extracts_domain_for_pattern(self):
        src = _src(TC_PATH)
        # Should reference domain when building near-miss pattern
        assert "domain" in src
        assert "Near-miss" in src or "near_miss" in src

    def test_uses_build_jsonl_entry(self):
        src = _src(TC_PATH)
        assert "build_jsonl_entry" in src

    def test_uses_append_knowledge_jsonl(self):
        src = _src(TC_PATH)
        assert "append_knowledge_jsonl" in src

    def test_knowledge_type_is_pattern(self):
        src = _src(TC_PATH)
        assert '"pattern"' in src or "'pattern'" in src

    def test_confidence_set_to_0_6(self):
        src = _src(TC_PATH)
        assert "0.6" in src

    def test_uses_near_miss_avg_confidence(self):
        src = _src(TC_PATH)
        assert "near_miss_avg_confidence" in src

    def test_fail_open(self):
        src = _src(TC_PATH)
        # The near-miss block must be wrapped in try/except
        nm_idx = src.index("near_miss")
        # find the surrounding try block
        block = src[max(0, nm_idx - 300): nm_idx + 800]
        assert "try:" in block
        assert "except Exception:" in block

    def test_file_under_300_lines(self):
        assert _lines(TC_PATH) < 300
