import tempfile
import unittest
from pathlib import Path

from gnos.cli.main import main
from gnos.core.hash import sha256_hex, canonicalize_bytes


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

                os.chdir(root)
                main(["init"])
                (root / "a.md").write_text("# A\n", encoding="utf-8")
                main(["add", "a.md"])

                doc_id = sha256_hex(canonicalize_bytes((root / "a.md").read_bytes()))
                out_path = root / "out.md"
                exit_code = main(["materialize", "doc", doc_id, "--output", str(out_path)])
                self.assertEqual(exit_code, 0)
                self.assertEqual(out_path.read_text(encoding="utf-8"), "# A\n")
            finally:
                os.chdir(old_cwd)


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