"""Tests for the Audit Logger."""

from contextguard.logger import AuditLogger


class TestJSONBackend:
    def test_write_and_read(self, tmp_path):
        log_path = tmp_path / "test.jsonl"
        logger = AuditLogger(backend="json", path=log_path)

        logger.log(
            risk_score=0.5,
            risk_level="medium",
            detected_categories=["injection"],
            sanitized=False,
            blocked=False,
            prompt_preview="test prompt",
        )

        logs = logger.get_logs()
        assert len(logs) == 1
        assert logs[0]["risk_score"] == 0.5
        assert logs[0]["risk_level"] == "medium"
        logger.close()

    def test_multiple_entries(self, tmp_path):
        log_path = tmp_path / "test.jsonl"
        logger = AuditLogger(backend="json", path=log_path)

        for i in range(5):
            logger.log(
                risk_score=i * 0.2,
                risk_level="low",
                detected_categories=[],
            )

        logs = logger.get_logs()
        assert len(logs) == 5
        logger.close()


class TestSQLiteBackend:
    def test_write_and_read(self, tmp_path):
        db_path = tmp_path / "test.db"
        logger = AuditLogger(backend="sqlite", path=db_path)

        logger.log(
            risk_score=0.8,
            risk_level="high",
            detected_categories=["injection", "secrets"],
            blocked=True,
            prompt_preview="malicious prompt",
        )

        logs = logger.get_logs()
        assert len(logs) == 1
        assert logs[0]["risk_score"] == 0.8
        assert logs[0]["blocked"] is True
        assert "injection" in logs[0]["detected_categories"]
        logger.close()

    def test_auto_block(self, tmp_path):
        db_path = tmp_path / "test.db"
        logger = AuditLogger(backend="sqlite", path=db_path, block_threshold=0.5)

        entry = logger.log(
            risk_score=0.9,
            risk_level="high",
            detected_categories=["injection"],
        )
        assert entry.blocked is True
        logger.close()
