import tempfile
import unittest
from pathlib import Path

from gnos.cli.main import main
import gnos.chunking.registry as reg
from examples.gnos_example_derived_chunker.chunker import ExampleDerivedChunker


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

                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)
                data = json.loads((root / ".gnos" / "index.json").read_text(encoding="utf-8"))
                doc_id = list(data["documents"].keys())[0]
                manifest_hash = data["documents"][doc_id]["manifests"][0]
                reg._CHUNKERS["example-derived-v1"] = ExampleDerivedChunker()
                reg._SOURCES["example-derived-v1"] = "example"
                try:
                    exit_code = main(
                        [
                            "derive",
                            manifest_hash,
                            "--chunking",
                            "example-derived-v1",
                            "--verbose",
                        ]
                    )
                finally:
                    reg._CHUNKERS.pop("example-derived-v1", None)
                    reg._SOURCES.pop("example-derived-v1", None)
                self.assertEqual(exit_code, 0)
            finally:
                os.chdir(old_cwd)


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