import os
import tempfile

from neurovault.network.sync_log import SyncLog


def test_sync_log_append_and_get_since():
    with tempfile.NamedTemporaryFile(suffix=".log", delete=False) as handle:
        path = handle.name
    try:
        log = SyncLog(path)
        log.append("memory_added", {"id": "a"})
        log.append("entity_upserted", {"id": "b"})

        entries = log.get_since(0)
        assert len(entries) == 2
        assert entries[0]["op"] == "memory_added"
        assert log.get_latest_seq() == 2
    finally:
        os.unlink(path)


def test_sync_log_integrity_detects_tamper():
    with tempfile.NamedTemporaryFile(suffix=".log", delete=False) as handle:
        path = handle.name
    try:
        log = SyncLog(path)
        log.append("test", {"data": "value"})
        assert log.verify_integrity()

        # Tamper in-memory payload to simulate corruption.
        log._entries[0]["data"] = {"data": "changed"}
        assert not log.verify_integrity()
    finally:
        os.unlink(path)
