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

from gnos.cli.main import main


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

                os.chdir(root)
                self.assertEqual(main(["init"]), 0)
                (root / "a.md").write_text("# A\n", encoding="utf-8")
                self.assertEqual(main(["add", "a.md"]), 0)

                buf = io.StringIO()
                with redirect_stdout(buf):
                    self.assertEqual(main(["list", "--documents"]), 0)
                docs = [line.strip() for line in buf.getvalue().splitlines() if line.strip()]
                self.assertEqual(len(docs), 1)

                buf = io.StringIO()
                with redirect_stdout(buf):
                    self.assertEqual(main(["list", "--objects"]), 0)
                objs = [line.strip() for line in buf.getvalue().splitlines() if line.strip()]
                self.assertGreaterEqual(len(objs), 1)
            finally:
                os.chdir(old_cwd)


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