# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-non-repudiation-loss-when-a2a-v1-0-signed-task-frames-are-re-serialized-across-a-delegation-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-non-repudiation-loss-when-a2a-v1-0-signed-task-frames-are-re-serialized-across-a-delegation-hop.warrant.json
# Markdown SHA-256:   298c330dac75f1be3ea7394afd75b1a0522fec88e5520111aa0a8dc35f00c0c7
# Code AST SHA-256:   8d153cbc344ae511472ad23c751b69aa45d1f6baac796d4154e69306f9c8de05
# Verified Classes:   NonRepudiationBroken, SignedFrame
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class NonRepudiationBroken(RuntimeError):
    """Raised when a received A2A task frame cannot be attributed to a
    verifiable signer under any supported canonicalization profile and
    carries no valid chained signature from a delegation hop."""


@dataclass(frozen=True)
class SignedFrame:
    body: dict
    signer_kid: str
    digest: str
    jws: str
    chained_from: Optional[str] = None  # prior signer's kid, if this is a re-sign


def canonical_digest(body: dict) -> str:
    # JCS-style: sorted keys, no whitespace, UTF-8, deterministic number repr.
    canon = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(canon.encode("utf-8")).hexdigest()


def verify_frame(frame: SignedFrame, trusted_kids: set[str]) -> str:
    """Return the effective author kid, or raise NonRepudiationBroken."""
    recomputed = canonical_digest(frame.body)

    if recomputed == frame.digest and frame.signer_kid in trusted_kids:
        return frame.signer_kid

    # Attempt chained-signature acceptance: the intermediate must have
    # back-referenced the prior signer, and itself be trusted.
    if frame.chained_from and frame.signer_kid in trusted_kids:
        if frame.chained_from not in trusted_kids:
            raise NonRepudiationBroken(
                f"chained signature references untrusted prior kid {frame.chained_from!r}"
            )
        # Effective author is the intermediate only for the hop it warrants;
        # the original author is recorded as attested, not authoritative.
        return frame.signer_kid

    raise NonRepudiationBroken(
        f"digest mismatch for signer {frame.signer_kid!r}: "
        f"expected {frame.digest}, recomputed {recomputed}; "
        f"no chained signature from a trusted intermediate"
    )


def route_frame(frame: SignedFrame, router_kid: str, trusted_kids: set[str]) -> SignedFrame:
    """Intermediates must extend the transport envelope, never the signed body."""
    # Correct behavior: do not mutate frame.body; wrap it.
    envelope = {"payload": frame.body, "routed_by": router_kid}
    # Re-sign over the envelope's own canonical form, chaining to prior signer.
    new_digest = canonical_digest(envelope)
    return SignedFrame(
        body=envelope,
        signer_kid=router_kid,
        digest=new_digest,
        jws="<router-jws-over-envelope>",
        chained_from=frame.signer_kid,
    )
