import tempfile
import unittest
from pathlib import Path
from unittest import mock

from gnos.core.add import AddError, add_collection
from gnos.core.store import ObjectStore


class TestAddCollectionAtomic(unittest.TestCase):
    def test_add_collection_atomic_no_objects_on_failure(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            store = ObjectStore(root / ".gnos")
            store.init()

            docs = root / "docs"
            docs.mkdir()
            (docs / "a.md").write_text("# A\n", encoding="utf-8")
            (docs / "b.md").write_text("# B\n", encoding="utf-8")

            with mock.patch("gnos.core.add.dump_collection_bytes", side_effect=RuntimeError("boom")):
                with self.assertRaises(RuntimeError):
                    add_collection(docs, store)

            objects = list((root / ".gnos" / "objects").rglob("*"))
            files = [p for p in objects if p.is_file()]
            self.assertEqual(len(files), 0)
            self.assertFalse((root / ".gnos" / "index.json").exists())


if __name__ == "__main__":
    unittest.main()

