"""Comprehensive tests for contradiction detection engine."""

from datetime import datetime, timezone, timedelta
from mnemosynth.core.types import MemoryNode, MemoryType, MemoryStatus
from mnemosynth.core.config import MnemosynthConfig
from mnemosynth.engine.contradiction import ContradictionEngine


class TestContradictionEngine:
    def setup_method(self):
        self.config = MnemosynthConfig(data_dir="/tmp/mnemosynth_test_contra")
        self.engine = ContradictionEngine(config=self.config)
        self.engine.threshold = 0.3  # Lower threshold for keyword-based tests

    def _make_memory(self, content: str, days_ago: int = 0) -> MemoryNode:
        node = MemoryNode.create(content=content, memory_type=MemoryType.SEMANTIC)
        if days_ago > 0:
            node.created_at = datetime.now(timezone.utc) - timedelta(days=days_ago)
        return node

    # ── Clear contradictions ──────────────────────────────────

    def test_antonym_contradiction(self):
        a = self._make_memory("User prefers dark mode always")
        b = self._make_memory("User prefers light mode never dark")
        result = self.engine.check_pair(a, b)
        assert result is not None, "Should detect dark/light contradiction"
        assert result.score > 0

    def test_preference_contradiction(self):
        a = self._make_memory("The user does like Python for backend development work")
        b = self._make_memory("The user does hate Python for backend development work")
        result = self.engine.check_pair(a, b)
        assert result is not None, "Should detect like/hate contradiction"

    def test_boolean_contradiction(self):
        a = self._make_memory("The feature is true enabled yes")
        b = self._make_memory("The feature is false disabled no")
        result = self.engine.check_pair(a, b)
        assert result is not None

    # ── Non-contradictory pairs ───────────────────────────────

    def test_unrelated_no_contradiction(self):
        a = self._make_memory("User prefers dark mode")
        b = self._make_memory("The project uses React")
        result = self.engine.check_pair(a, b)
        assert result is None, "Unrelated memories should not contradict"

    def test_same_memory_no_contradiction(self):
        a = self._make_memory("User likes Python")
        result = self.engine.check_pair(a, a)
        assert result is None, "Same memory should not contradict itself"

    def test_complementary_no_contradiction(self):
        a = self._make_memory("User likes Python")
        b = self._make_memory("User likes JavaScript")
        result = self.engine.check_pair(a, b)
        # These should NOT be contradictory (user can like both)
        assert result is None or result.score < 0.5

    # ── Scan functionality ────────────────────────────────────

    def test_scan_empty_list(self):
        report = self.engine.scan([])
        assert report.contradictions_found == 0
        assert report.total_checked == 0

    def test_scan_with_contradictions(self):
        memories = [
            self._make_memory("User always prefers dark mode"),
            self._make_memory("User never prefers dark mode"),
            self._make_memory("Project uses React"),
        ]
        report = self.engine.scan(memories)
        assert report.total_checked > 0

    def test_scan_skips_deprecated(self):
        a = self._make_memory("User likes tabs")
        a.status = MemoryStatus.DEPRECATED
        b = self._make_memory("User likes spaces")
        report = self.engine.scan([a, b])
        # Deprecated memories are filtered out, only 1 active → 0 pairs
        assert report.total_checked == 0

    # ── Resolution ────────────────────────────────────────────

    def test_resolve_keeps_newer(self):
        old = self._make_memory("User likes Java", days_ago=30)
        new = self._make_memory("User likes Python", days_ago=0)

        from mnemosynth.engine.contradiction import Contradiction
        contradiction = Contradiction(memory_a=old, memory_b=new, score=0.9)

        winner = self.engine.resolve(contradiction)
        assert winner.id == new.id
        assert old.status == MemoryStatus.DEPRECATED
        assert old.superseded_by == new.id

    def test_resolve_marks_as_resolved(self):
        a = self._make_memory("X", days_ago=10)
        b = self._make_memory("Y", days_ago=0)

        from mnemosynth.engine.contradiction import Contradiction
        c = Contradiction(memory_a=a, memory_b=b, score=0.8)

        self.engine.resolve(c)
        assert c.resolved is True

    # ── Explanation ───────────────────────────────────────────

    def test_explanation_generated(self):
        a = self._make_memory("User prefers dark mode")
        b = self._make_memory("User prefers light mode")
        result = self.engine.check_pair(a, b)
        if result:
            assert len(result.explanation) > 0
