import json
import tempfile
import unittest
from pathlib import Path

import gnos.chunking.registry as reg
from examples.gnos_example_derived_chunker.chunker import ExampleDerivedChunker
from gnos.cli.main import main
from gnos.core.hash import sha256_hex
from gnos.core.store import ObjectStore
from gnos.manifest.codec import canonical_json_bytes


class TestDerivedAttestModes(unittest.TestCase):
    def test_derived_attest_shallow_ok_full_fails(self) -> None:
        obj = {
            "type": "derived-manifest",
            "version": 1,
            "doc_id": "0" * 64,
            "source_manifest": "1" * 64,
            "chunking": {"method": "example-derived-v1", "params": {}},
            "chunks": [{"hash": sha256_hex(b"data")}],
        }
        manifest_bytes = json.dumps(obj, separators=(",", ":"), sort_keys=False).encode("utf-8")
        manifest_hash = sha256_hex(canonical_json_bytes(obj))

        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            old_cwd = Path.cwd()
            try:
                import os

                os.chdir(root)
                store = ObjectStore(root / ".gnos")
                store.init()
                store.put(manifest_hash, manifest_bytes)
                store.put(sha256_hex(b"data"), b"data")

                reg._CHUNKERS["example-derived-v1"] = ExampleDerivedChunker()
                reg._SOURCES["example-derived-v1"] = "example"
                try:
                    self.assertEqual(main(["attest", "manifest", manifest_hash, "--shallow"]), 0)
                    self.assertEqual(main(["attest", "manifest", manifest_hash]), 2)
                finally:
                    reg._CHUNKERS.pop("example-derived-v1", None)
                    reg._SOURCES.pop("example-derived-v1", None)
            finally:
                os.chdir(old_cwd)


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