import io
import tempfile
import unittest
from contextlib import redirect_stdout
from pathlib import Path

from gnos.cli.main import main
from gnos.core.store import ObjectStore
from gnos.manifest.codec import load_collection_bytes


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

                os.chdir(root)
                main(["init"])
                (root / "docs").mkdir()
                (root / "docs" / "a.md").write_text("# A\n", encoding="utf-8")
                (root / "docs" / "b.md").write_text("# B\n", encoding="utf-8")
                main(["add", "-C", "docs"])

                store = ObjectStore(Path(".gnos"))
                collection_ids = []
                for obj in store.objects_dir().rglob("*"):
                    if not obj.is_file():
                        continue
                    try:
                        blob = obj.read_bytes()
                        load_collection_bytes(blob)
                        collection_ids.append(obj.name)
                    except Exception:
                        continue
                self.assertEqual(len(collection_ids), 1)

                buf = io.StringIO()
                with redirect_stdout(buf):
                    exit_code = main(["status", "--collections"])
                self.assertEqual(exit_code, 0)
                output = buf.getvalue()
                self.assertIn(collection_ids[0], output)
                self.assertIn("collections:", output)
                self.assertIn("doc-manifests:", output)
                self.assertIn("collection-manifests:", output)
                self.assertIn("derived-manifests:", output)
            finally:
                os.chdir(old_cwd)


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