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

from gnos.cli.main import main


class TestCliInspect(unittest.TestCase):
    def test_inspect_manifest_and_chunk(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)

                index = json.loads((root / ".gnos" / "index.json").read_text(encoding="utf-8"))
                doc_id, doc_entry = next(iter(index["documents"].items()))
                self.assertTrue(doc_id)
                manifest_hash = doc_entry["manifests"][0]
                chunk_hash = index["manifests"][manifest_hash]["chunks"][0]["hash"]

                buf = io.StringIO()
                with redirect_stdout(buf):
                    self.assertEqual(main(["inspect", manifest_hash]), 0)
                out = buf.getvalue()
                self.assertIn("manifest:", out)
                self.assertIn('"type": "doc-manifest"', out)

                buf = io.StringIO()
                with redirect_stdout(buf):
                    self.assertEqual(main(["inspect", chunk_hash]), 0)
                out = buf.getvalue()
                self.assertIn("chunk:", out)
                self.assertIn("size:", out)

            finally:
                os.chdir(old_cwd)


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