# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Tests for the 5 Grounded Knowledge integration items (v10.37.54)."""
import json


class TestSearchScoring:
    """Item 1: SOURCE_WEIGHT in compute_salience."""

    def test_source_weight_dict_exists(self):
        from pulse.brain.index.search_utils import SOURCE_WEIGHT
        assert "CONFIRMED" in SOURCE_WEIGHT
        assert "CONVERSATIONAL" in SOURCE_WEIGHT
        assert SOURCE_WEIGHT["CONFIRMED"] > SOURCE_WEIGHT["CONVERSATIONAL"]

    def test_ground_weight_param(self):
        """compute_salience accepts ground_weight and applies it."""
        from pulse.brain.index.search_utils import compute_salience
        config = {"search": {}}
        base = compute_salience(0.5, 1, config, 3.0, ground_weight=1.0)
        weighted = compute_salience(0.5, 1, config, 3.0, ground_weight=0.35)
        assert weighted < base, "ground_weight=0.35 should reduce score"
        assert weighted > 0, "Score should still be positive"

    def test_source_type_in_search_hit(self):
        """Search hits from SQLite should include source_type field."""
        from pulse.core.brain_db import get_conn
        conn = get_conn()
        row = conn.execute("SELECT source_type FROM lessons LIMIT 1").fetchone()
        assert row is not None, "lessons table should have rows"
        assert row["source_type"] in ("CONVERSATIONAL", "INFERRED", "OBSERVED", "CONFIRMED")


class TestEpistemicTags:
    """Item 2: [CONFIRMED] tag in epistemic qualifiers."""

    def test_confirmed_item_gets_tag(self):
        from pulse.brain.workspace.epistemic import apply_epistemic_qualifiers
        item = {"text": "Test confirmed", "confidence": 0.9,
                "evidence_count": 5, "source_type": "CONFIRMED",
                "validity": "valid", "_wilson_lower": 0.7}
        result = apply_epistemic_qualifiers(dict(item))
        assert "[CONFIRMED]" in result["text"]
        assert "[UNCERTAIN]" not in result["text"]

    def test_conversational_no_confirmed_tag(self):
        from pulse.brain.workspace.epistemic import apply_epistemic_qualifiers
        item = {"text": "Test conv", "confidence": 0.8,
                "evidence_count": 1, "source_type": "CONVERSATIONAL"}
        result = apply_epistemic_qualifiers(dict(item))
        assert "[CONFIRMED]" not in result["text"]

    def test_confirmed_flag_set(self):
        from pulse.brain.workspace.epistemic import apply_epistemic_qualifiers
        item = {"text": "Flag test", "confidence": 0.9,
                "evidence_count": 5, "source_type": "CONFIRMED",
                "validity": "valid", "_wilson_lower": 0.7}
        result = apply_epistemic_qualifiers(dict(item))
        assert result.get("_confirmed") is True


class TestBootGroundTruth:
    """Item 3: Ground truth section in boot context."""

    def test_get_confirmed_titles_function_exists(self):
        from pulse.brain.boot.loaders import _get_confirmed_titles
        titles = _get_confirmed_titles("lessons", limit=3)
        assert isinstance(titles, list)

    def test_load_recent_brain_has_ground_truth_key(self):
        from pulse.brain.boot.loaders import load_recent_brain
        data = load_recent_brain()
        assert "confirmed_ground_truth" in data
        assert isinstance(data["confirmed_ground_truth"], list)


class TestHookOutput:
    """Item 4: Hook output surfaces CONFIRMED items."""

    def test_briefing_handles_confirmed_hits(self):
        """format_briefing should not crash with _confirmed items."""
        from pulse.brain.brain_query.briefing import format_briefing
        results = {
            "results": {"wins": [
                {"text": "[CONFIRMED] Use UTF-8", "score": 0.9, "_confirmed": True},
                {"text": "Regular item", "score": 0.5},
            ]},
            "total_results": 2,
            "elapsed_ms": 100,
        }
        output = format_briefing("test query", results)
        assert isinstance(output, str)


class TestPulseConfirm:
    """Item 5: pulse confirm CLI command."""

    def test_confirm_route_exists(self):
        """main.py should have a 'confirm' route."""
        with open("pulse/cli/main.py") as f:
            content = f.read()
        assert "confirm" in content, "pulse confirm route must exist"

    def test_cmd_confirm_function_exists(self):
        """cmd_manage_data.py should have _cmd_confirm."""
        with open("pulse/cli/cmd_manage_data.py") as f:
            content = f.read()
        assert "_cmd_confirm" in content, "_cmd_confirm function must exist"
