import tempfile
import unittest
from pathlib import Path

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


class TestAttestCollection(unittest.TestCase):
    def test_attest_collection_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"])

                # Build a collection with the doc_id from index.json
                index = (root / ".gnos" / "index.json").read_text(encoding="utf-8")
                import json

                data = json.loads(index)
                doc_id = list(data["documents"].keys())[0]

                collection = CollectionManifest(
                    type="collection-manifest",
                    version=1,
                    documents=[CollectionEntry(doc_id=doc_id, path="a.md")],
                )
                blob = dump_collection_bytes(collection)
                collection_id = sha256_hex(blob)

                store = ObjectStore(root / ".gnos")
                store.put(collection_id, blob)

                exit_code = main(["attest", "manifest", collection_id])
                self.assertEqual(exit_code, 0)
            finally:
                os.chdir(old_cwd)

    def test_attest_collection_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", "manifest", "0" * 64])
                self.assertEqual(exit_code, 1)
            finally:
                os.chdir(old_cwd)


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