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

from gnos.cli.main import main


class TestCliMaterializeStdout(unittest.TestCase):
    def test_materialize_doc_stdout(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)
                content = "hello\n"
                (root / "a.txt").write_text(content, encoding="utf-8")
                self.assertEqual(main(["add", "a.txt"]), 0)

                index = (root / ".gnos" / "index.json").read_text(encoding="utf-8")
                doc_id = next(iter(__import__("json").loads(index)["documents"].keys()))

                buf = io.BytesIO()
                wrapper = io.TextIOWrapper(buf, encoding="utf-8")
                with redirect_stdout(wrapper):
                    self.assertEqual(main(["materialize", "doc", doc_id, "--output", "-"]), 0)
                wrapper.flush()
                self.assertIn(content.encode("utf-8"), buf.getvalue())
            finally:
                os.chdir(old_cwd)


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