import tempfile
import unittest
from pathlib import Path

from gnos.cli.main import main


class TestMaterializeCollection(unittest.TestCase):
    def test_materialize_collection(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            old_cwd = Path.cwd()
            try:
                import os

                os.chdir(root)
                main(["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")

                # Add collection to get collection_id
                exit_code = main(["add", "-C", str(docs)])
                self.assertEqual(exit_code, 0)

                # Read collection_id from store by scanning objects
                store_dir = root / ".gnos" / "objects"
                collection_id = None
                for obj in store_dir.rglob("*"):
                    if not obj.is_file():
                        continue
                    data = obj.read_bytes()
                    if b"collection-manifest" in data:
                        collection_id = obj.name
                        break
                self.assertIsNotNone(collection_id)

                out_dir = root / "out"
                exit_code = main(["materialize", "collection", collection_id, "--dir", str(out_dir)])
                self.assertEqual(exit_code, 0)
                self.assertTrue((out_dir / "a.md").exists())
                self.assertTrue((out_dir / "b.md").exists())
            finally:
                os.chdir(old_cwd)


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