import tempfile
import unittest
from pathlib import Path

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


class TestAttestDoc(unittest.TestCase):
    def test_attest_doc_ok(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()))
                exit_code = main(["attest", "doc", doc_id])
                self.assertEqual(exit_code, 0)
            finally:
                os.chdir(old_cwd)

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

                os.chdir(root)
                main(["init"])
                exit_code = main(["attest", "doc", "0" * 64])
                self.assertEqual(exit_code, 2)
            finally:
                os.chdir(old_cwd)


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