#!/usr/bin/env python3
"""Quality Gate: Hash Determinism.

Verifies that canonical_hash_jcs_sha256 produces stable, reproducible digests
for a set of known test vectors. Exits 0 on success, 1 on failure.
"""

from __future__ import annotations

import hashlib
import sys

from abi_control_core.sdk.canonical_hash import canonical_hash_jcs_sha256, jcs_serialize

# Known test vectors: (input_object, expected_canonical_bytes)
TEST_VECTORS = [
    ({}, b"{}"),
    ({"a": 1}, b'{"a":1}'),
    ({"b": 2, "a": 1}, b'{"a":1,"b":2}'),
    ([1, 2, 3], b"[1,2,3]"),
    (None, b"null"),
    (True, b"true"),
    ("hello", b'"hello"'),
]


def main() -> int:
    errors: list[str] = []

    # Test JCS serialization stability
    for obj, expected_bytes in TEST_VECTORS:
        actual = jcs_serialize(obj)
        if actual != expected_bytes:
            errors.append(
                f"JCS mismatch: {obj!r} → {actual!r} (expected {expected_bytes!r})"
            )

    # Test hash stability (same input → same digest, always)
    stability_obj = {
        "schema_version": "run-manifest/1.0",
        "run_id": "abcd1234",
        "verdict": "pass",
        "summary": {"total": 5, "passed": 5, "failed": 0},
    }
    digests = {canonical_hash_jcs_sha256(stability_obj) for _ in range(100)}
    if len(digests) != 1:
        errors.append(f"Hash instability: {len(digests)} distinct digests for same input")

    # Verify known hash vector
    expected_hash = hashlib.sha256(b"{}").hexdigest()
    actual_hash = canonical_hash_jcs_sha256({})
    if actual_hash != expected_hash:
        errors.append(f"Known vector mismatch: sha256({{}}) = {actual_hash} (expected {expected_hash})")

    if errors:
        print(f"FAIL: {len(errors)} determinism error(s):")
        for err in errors:
            print(f"  - {err}")
        return 1

    print(f"PASS: {len(TEST_VECTORS)} JCS vectors + hash stability verified")
    return 0


if __name__ == "__main__":
    sys.exit(main())
