"""
Content Digest Verifier

Verifies that the content-digest proof matches the canonical region.
"""

from __future__ import annotations

import base64
import hashlib
import logging
from typing import TYPE_CHECKING

from receipts.verifiers.verdict import ProofVerdict

if TYPE_CHECKING:
    from receipts.models_v1 import ReceiptV1

logger = logging.getLogger(__name__)


def verify_content_digest(receipt: "ReceiptV1") -> ProofVerdict:
    """
    Verify the content-digest proof.

    Recomputes the SHA-256 hash of the canonical region and compares
    it to the claimed digest in the content-digest proof.

    Args:
        receipt: The ReceiptV1 to verify

    Returns:
        ProofVerdict with ok/fail status
    """
    from jcs import canonicalize as jcs_canonicalize
    from receipts.models_v1 import ContentDigestProof

    # Get the content-digest proof
    proof = receipt.get_proof("content-digest")
    if proof is None:
        return ProofVerdict.fail(
            kind="content-digest",
            reason="No content-digest proof present",
        )

    if not isinstance(proof, ContentDigestProof):
        return ProofVerdict.fail(
            kind="content-digest",
            reason=f"Invalid proof type: {type(proof).__name__}",
        )

    # Get the canonical region
    try:
        canonical_region = receipt.to_canonical_region()
        jcs_bytes = jcs_canonicalize(canonical_region)
    except Exception as e:
        return ProofVerdict.fail(
            kind="content-digest",
            reason=f"Failed to canonicalize: {e}",
        )

    # Compute expected digest
    try:
        computed_digest = hashlib.sha256(jcs_bytes).digest()
        computed_b64 = base64.b64encode(computed_digest).decode("ascii")
    except Exception as e:
        return ProofVerdict.fail(
            kind="content-digest",
            reason=f"Failed to compute digest: {e}",
        )

    # Compare
    if proof.value != computed_b64:
        return ProofVerdict.fail(
            kind="content-digest",
            reason="Digest mismatch",
            details={
                "claimed": proof.value[:32] + "...",
                "computed": computed_b64[:32] + "...",
            },
        )

    return ProofVerdict.ok(
        kind="content-digest",
        reason=f"Digest verified (alg={proof.alg})",
    )
