"""Tests for NovyxCheckpointer."""
import json
import pytest
from unittest.mock import patch, Mock, MagicMock


# ============================================================================
# Import Tests
# ============================================================================

def test_checkpointer_import():
    """Test that NovyxCheckpointer can be imported without NovyxConfig error."""
    from novyx_langchain.checkpointer import NovyxCheckpointer
    assert NovyxCheckpointer is not None


def test_checkpointer_import_from_package():
    """Test that NovyxCheckpointer is exported from the package."""
    from novyx_langchain import NovyxCheckpointer
    assert NovyxCheckpointer is not None


# ============================================================================
# NovyxCheckpointer Tests (requires langgraph)
# ============================================================================

class TestNovyxCheckpointer:
    """Tests for the LangGraph checkpointer."""

    @pytest.fixture
    def mock_sdk(self):
        with patch("novyx_langchain.memory.Novyx") as MockNovyx:
            mock_client = Mock()
            MockNovyx.return_value = mock_client
            mock_client.remember.return_value = {"uuid": "cp-123"}
            mock_client.memories.return_value = []
            mock_client.forget.return_value = True
            mock_client.rollback.return_value = {
                "success": True,
                "artifacts_restored": 2,
            }
            yield mock_client

    def test_init(self, mock_sdk):
        """Test checkpointer initialization."""
        try:
            from novyx_langchain import NovyxCheckpointer

            cp = NovyxCheckpointer(
                api_key="nram_test_12345678",
                namespace="test-ns",
            )
            assert cp.namespace == "test-ns"
        except ImportError:
            pytest.skip("langgraph not installed")

    def test_thread_tag(self, mock_sdk):
        """Test thread tag generation."""
        try:
            from novyx_langchain import NovyxCheckpointer

            cp = NovyxCheckpointer(api_key="nram_test_12345678")
            assert cp._thread_tag("conv-123") == "thread:conv-123"
        except ImportError:
            pytest.skip("langgraph not installed")

    def test_put_stores_checkpoint(self, mock_sdk):
        """Test that put() stores checkpoint via remember()."""
        try:
            from novyx_langchain import NovyxCheckpointer

            cp = NovyxCheckpointer(api_key="nram_test_12345678")

            config = {"configurable": {"thread_id": "thread-1"}}
            checkpoint = {"v": 1, "ts": "2026-02-20T10:00:00Z", "channel_values": {}}
            metadata = {}

            result = cp.put(config, checkpoint, metadata)

            assert "configurable" in result
            assert "checkpoint_id" in result["configurable"]
            mock_sdk.remember.assert_called_once()

            # Verify stored data includes thread_id
            call_kwargs = mock_sdk.remember.call_args[1]
            stored_data = json.loads(call_kwargs["observation"])
            assert stored_data["thread_id"] == "thread-1"
        except ImportError:
            pytest.skip("langgraph not installed")

    def test_get_tuple_returns_none_when_empty(self, mock_sdk):
        """Test get_tuple returns None when no checkpoints exist."""
        try:
            from novyx_langchain import NovyxCheckpointer

            cp = NovyxCheckpointer(api_key="nram_test_12345678")
            config = {"configurable": {"thread_id": "thread-1"}}

            result = cp.get_tuple(config)
            assert result is None
        except ImportError:
            pytest.skip("langgraph not installed")

    def test_clear_thread(self, mock_sdk):
        """Test clearing all checkpoints for a thread."""
        try:
            from novyx_langchain import NovyxCheckpointer

            mock_sdk.memories.return_value = [
                {"uuid": "cp-1", "observation": "test", "tags": [], "importance": 5}
            ]

            cp = NovyxCheckpointer(api_key="nram_test_12345678")
            count = cp.clear_thread("thread-1")

            mock_sdk.memories.assert_called()
        except ImportError:
            pytest.skip("langgraph not installed")
