import tempfile
import unittest
from pathlib import Path

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


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

                os.chdir(root)
                Path("a.txt").write_text("hello\n", encoding="utf-8")
                self.assertEqual(main(["init"]), 0)

                # Override default chunk_size and ensure it lands in the manifest.
                self.assertEqual(
                    main(
                        [
                            "add",
                            "a.txt",
                            "--format",
                            "text",
                            "--chunking",
                            "sequential-v1",
                            "--chunking-params",
                            "chunk_size=2",
                            "--verbose",
                        ]
                    ),
                    0,
                )

                store = ObjectStore(Path(".gnos"))
                objects = [p for p in store.objects_dir().rglob("*") if p.is_file()]
                # Find the first stored doc-manifest.
                manifest_bytes = None
                for p in objects:
                    b = p.read_bytes()
                    if b.startswith(b"{") and b'"type":"doc-manifest"' in b:
                        manifest_bytes = b
                        break
                self.assertIsNotNone(manifest_bytes)

                manifest = load_manifest_bytes(manifest_bytes)  # type: ignore[arg-type]
                self.assertEqual(manifest.chunking["method"], "sequential-v1")
                self.assertEqual(manifest.chunking["params"]["chunk_size"], 2)
            finally:
                os.chdir(old)


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