"""Tests for decision audit logger."""

import json
import tempfile
from pathlib import Path

import pytest

from oclawma.self_improvement.decision_audit_logger import DecisionAuditLogger


class TestDecisionAuditLogger:
    """Tests for DecisionAuditLogger."""

    @pytest.fixture
    def temp_dir(self):
        """Create temporary directory for tests."""
        with tempfile.TemporaryDirectory() as tmp:
            yield Path(tmp)

    @pytest.fixture
    def logger(self, temp_dir):
        """Create logger with temp path."""
        return DecisionAuditLogger(
            db_path=str(temp_dir / "decisions.json"),
        )

    def test_log_decision(self, logger, temp_dir):
        """Test logging a decision."""
        decision_id = logger.log_decision(
            decision="Use Python for this task",
            context="User wants a script",
            expected="success",
        )

        assert decision_id is not None
        assert len(decision_id) > 0

        # Verify it was saved
        data = json.loads((temp_dir / "decisions.json").read_text())
        assert len(data["decisions"]) == 1
        assert data["decisions"][0]["decision"] == "Use Python for this task"

    def test_record_outcome(self, logger):
        """Test recording an outcome."""
        # Log decision
        decision_id = logger.log_decision("Use git rebase", "", "success")

        # Record outcome
        result = logger.record_outcome(decision_id, "Merge conflict occurred", False)

        assert result is True

        # Verify
        decision = logger.get_decision(decision_id)
        assert decision["outcome"] == "Merge conflict occurred"
        assert decision["correct"] is False

    def test_record_outcome_not_found(self, logger):
        """Test recording outcome for non-existent decision."""
        result = logger.record_outcome("non-existent-id", "outcome", True)
        assert result is False

    def test_get_stats(self, logger):
        """Test getting statistics."""
        # Log some decisions
        id1 = logger.log_decision("Decision 1", "", "success")
        id2 = logger.log_decision("Decision 2", "", "success")
        logger.log_decision("Decision 3", "", "success")

        # Record outcomes
        logger.record_outcome(id1, "Worked well", True)
        logger.record_outcome(id2, "Failed", False)
        # id3 has no outcome

        # Reload logger to ensure we're reading from disk
        stats = logger.get_stats()

        assert stats["total"] == 3
        assert stats["with_outcome"] == 2
        assert stats["pending"] == 1
        assert stats["correct"] == 1
        assert stats["incorrect"] == 1
        assert stats["accuracy"] == 50.0

    def test_get_stats_empty(self, logger):
        """Test stats with no decisions."""
        stats = logger.get_stats()

        assert stats["total"] == 0
        assert stats["accuracy"] == 0

    def test_list_recent(self, logger):
        """Test listing recent decisions."""
        # Log several decisions
        for i in range(5):
            logger.log_decision(f"Decision {i}")

        recent = logger.list_recent(limit=3)

        assert len(recent) == 3
        assert recent[0]["decision"] == "Decision 2"
        assert recent[2]["decision"] == "Decision 4"

    def test_get_decision(self, logger):
        """Test getting a specific decision."""
        decision_id = logger.log_decision("Specific decision")

        decision = logger.get_decision(decision_id)

        assert decision is not None
        assert decision["decision"] == "Specific decision"

    def test_get_decision_not_found(self, logger):
        """Test getting non-existent decision."""
        decision = logger.get_decision("non-existent")
        assert decision is None

    def test_decision_has_timestamp(self, logger):
        """Test that decisions have timestamps."""
        decision_id = logger.log_decision("Test")

        decision = logger.get_decision(decision_id)

        assert "timestamp" in decision
        assert len(decision["timestamp"]) > 0
