"""Tests for Contradiction Detector feature."""

import pytest

from locidb.core.db import LociDB


@pytest.fixture
def db(tmp_path):
    loci = LociDB(path=tmp_path / "test.loci")
    yield loci
    loci.close()


class TestConflictDetection:
    def test_no_conflicts_in_empty_db(self, db):
        assert db.check_conflicts() == []

    def test_no_conflicts_with_non_contradicting(self, db):
        db.memorize("We use Python for backend", entities=["python"])
        db.memorize("We use React for frontend", entities=["react"])
        assert db.check_conflicts() == []

    def test_detects_negation_conflict(self, db):
        db.memorize("We use PostgreSQL for the database", entities=["database"])
        db.memorize("We do not use PostgreSQL for the database", entities=["database"])
        conflicts = db.check_conflicts(similarity_threshold=0.7)
        assert len(conflicts) >= 1
        assert any("not" in c.reason.lower() or "negation" in c.reason.lower() for c in conflicts)

    def test_conflict_has_resolution_suggestion(self, db):
        db.memorize("Always deploy on Fridays", entities=["deploy"])
        db.memorize("Never deploy on Fridays", entities=["deploy"])
        conflicts = db.check_conflicts(similarity_threshold=0.7)
        if conflicts:
            assert conflicts[0].suggested_resolution != ""

    def test_conflict_warning_fields(self, db):
        db.memorize("We prefer tabs for indentation", entities=["style"])
        db.memorize("We do not prefer tabs for indentation", entities=["style"])
        conflicts = db.check_conflicts(similarity_threshold=0.7)
        if conflicts:
            c = conflicts[0]
            assert c.node_a is not None
            assert c.node_b is not None
            assert 0 <= c.similarity <= 1
            assert c.reason != ""

    def test_scope_filter(self, db):
        db.memorize("Use REST API", entities=["api"], scope="project:alpha")
        db.memorize("Do not use REST API", entities=["api"], scope="project:beta")
        # Same scope filter should find nothing (different scopes)
        conflicts_alpha = db.check_conflicts(scope="project:alpha", similarity_threshold=0.7)
        # The contradiction is across scopes, so filtered results may be empty
        # Just verify it doesn't crash
        assert isinstance(conflicts_alpha, list)
