import io
import tempfile
import unittest
from pathlib import Path
from unittest import mock

from gnos.cli.main import main
from gnos.core.store import ObjectStore


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

                os.chdir(root)
                self.assertEqual(main(["init"]), 0)
                store = ObjectStore(Path(".gnos"))
                self.assertEqual(len([p for p in store.objects_dir().rglob("*") if p.is_file()]), 0)

                fake_stdin = io.BytesIO(b"hello\n")
                with mock.patch("sys.stdin", io.TextIOWrapper(fake_stdin, encoding="utf-8")):
                    self.assertEqual(main(["add", "-", "--dry-run", "--verbose"]), 0)

                self.assertEqual(len([p for p in store.objects_dir().rglob("*") if p.is_file()]), 0)
                self.assertFalse((Path(".gnos") / "index.json").exists())
            finally:
                os.chdir(old)

    def test_add_stdin_commits_objects(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            old = Path.cwd()
            try:
                import os

                os.chdir(root)
                self.assertEqual(main(["init"]), 0)
                store = ObjectStore(Path(".gnos"))

                fake_stdin = io.BytesIO(b"hello\n")
                with mock.patch("sys.stdin", io.TextIOWrapper(fake_stdin, encoding="utf-8")):
                    self.assertEqual(main(["add", "-", "--verbose"]), 0)

                # Objects should exist after non-dry-run stdin add.
                self.assertGreater(len([p for p in store.objects_dir().rglob("*") if p.is_file()]), 0)
                # Index should be written.
                self.assertTrue((Path(".gnos") / "index.json").exists())
            finally:
                os.chdir(old)


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

