import io
import tempfile
import unittest
from contextlib import redirect_stderr
from pathlib import Path

from gnos.cli.main import main
from gnos.core.store import ObjectStore
from gnos.manifest.codec import dump_collection_bytes
from gnos.manifest.schema import CollectionEntry, CollectionManifest
from gnos.core.hash import sha256_hex


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

                os.chdir(root)
                self.assertEqual(main(["init"]), 0)

                # Collection references a doc_id that doesn't exist in the local index.
                bad_doc_id = "a" * 64
                collection = CollectionManifest(
                    type="collection-manifest",
                    version=1,
                    documents=[CollectionEntry(doc_id=bad_doc_id, path="x.txt")],
                )
                blob = dump_collection_bytes(collection)
                collection_id = sha256_hex(blob)
                store = ObjectStore(root / ".gnos")
                store.put(collection_id, blob)

                err = io.StringIO()
                with redirect_stderr(err):
                    exit_code = main(["attest", "manifest", collection_id])
                self.assertEqual(exit_code, 2)
                self.assertIn("attest failed:", err.getvalue())
            finally:
                os.chdir(old_cwd)


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