import tempfile
import unittest
from pathlib import Path

from gnos.core.attest import attest_any_manifest_bytes, AttestationError
from gnos.core.store import ObjectStore
from gnos.index.local import LocalIndex
from gnos.manifest.schema import CollectionManifest, CollectionEntry
from gnos.manifest.codec import dump_collection_bytes
from gnos.core.hash import sha256_hex


class TestAttestCollectionErrors(unittest.TestCase):
    def test_collection_hash_mismatch(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            store = ObjectStore(root / ".gnos")
            store.init()
            index = LocalIndex(root / ".gnos" / "index.json")

            collection = CollectionManifest(
                type="collection-manifest",
                version=1,
                documents=[CollectionEntry(doc_id="a" * 64, path="a.md")],
            )
            blob = dump_collection_bytes(collection)
            with self.assertRaises(AttestationError):
                attest_any_manifest_bytes(
                    blob,
                    store,
                    index,
                    expected_manifest_hash="0" * 64,
                )

    def test_collection_missing_doc(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            store = ObjectStore(root / ".gnos")
            store.init()
            index = LocalIndex(root / ".gnos" / "index.json")

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

            with self.assertRaises(AttestationError):
                attest_any_manifest_bytes(
                    blob,
                    store,
                    index,
                    expected_manifest_hash=collection_id,
                )


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