"""
TDD: Memory Hygiene — Selective Amnesia (NOT Nuclear Wipe)

Tests that startup performs intelligent memory pruning instead of
wiping all learned knowledge on every run.

Red-Green-Blue: These tests MUST fail first, then we implement.
"""

import pytest


class TestMemoryHygiene:
    """P0-2: Replace blank_start nuclear wipe with selective memory hygiene."""

    def test_high_confidence_entries_survive_hygiene(self):
        """High-confidence learned patterns must survive startup hygiene."""
        from GramAddict.core.qdrant_memory import ScreenMemoryDB

        db = ScreenMemoryDB()
        if not db.is_connected:
            pytest.skip("Qdrant not available")

        # Store a high-confidence entry
        db.store_screen("sig_high_conf", "HOME_FEED", confidence=0.95)

        # Run hygiene — this should NOT delete the high-confidence entry
        from GramAddict.core.qdrant_memory import memory_hygiene

        memory_hygiene()

        # Verify it survived
        result = db.get_screen_type("sig_high_conf", similarity_threshold=0.90)
        assert result == "HOME_FEED", "High-confidence entry was destroyed by memory_hygiene!"

    def test_low_confidence_entries_are_pruned(self):
        """Low-confidence (stale/poisoned) entries must be pruned during hygiene."""
        import uuid

        from GramAddict.core.qdrant_memory import ScreenMemoryDB

        db = ScreenMemoryDB()
        if not db.is_connected:
            pytest.skip("Qdrant not available")

        # Use a unique signature to prevent Qdrant state pollution from other tests
        unique_sig = f"sig_low_conf_{uuid.uuid4().hex[:8]}"

        # Store a low-confidence entry (representing a bad VLM guess)
        db.store_screen(unique_sig, "MODAL", confidence=0.2)

        # Run hygiene — this SHOULD delete the low-confidence entry
        from GramAddict.core.qdrant_memory import memory_hygiene

        memory_hygiene()

        # Verify it was pruned
        result = db.get_screen_type(unique_sig, similarity_threshold=0.99)
        assert result is None, "Low-confidence poisoned entry survived hygiene!"

    def test_memory_hygiene_function_exists(self):
        """The memory_hygiene function must be importable."""
        from GramAddict.core.qdrant_memory import memory_hygiene

        assert callable(memory_hygiene)

    def test_blank_start_is_not_default_config(self):
        """blank_start must NOT be true in the default config.
        It should only be available as a --blank-start CLI flag for explicit manual resets."""
        import yaml

        with open("config.yml", "r") as f:
            config = yaml.safe_load(f)

        blank_start = config.get("blank_start", False)
        assert blank_start is False or blank_start is None, (
            f"blank_start is {blank_start} in config.yml! "
            "This wipes ALL learned knowledge on every run, negating the entire learning system. "
            "Remove it or set to false. Use --blank-start CLI flag for explicit resets only."
        )


class TestScreenMemoryLRU:
    """P2-4: Replace nuclear 200-entry wipe with LRU eviction."""

    def test_screen_memory_does_not_nuke_at_200(self):
        """ScreenMemoryDB must NOT wipe the entire collection at 200 entries."""
        from GramAddict.core.qdrant_memory import ScreenMemoryDB

        db = ScreenMemoryDB()
        if not db.is_connected:
            pytest.skip("Qdrant not available")

        # Store 201 entries
        for i in range(201):
            db.store_screen(f"sig_lru_{i}", "HOME_FEED", confidence=0.9)

        # Verify that the first high-confidence entry still exists
        # (it should NOT have been nuked)
        result = db.get_screen_type("sig_lru_0", similarity_threshold=0.90)
        assert result is not None, (
            "ScreenMemoryDB nuked all 200+ entries! " "Must use LRU eviction instead of nuclear wipe."
        )
