# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-dpop-bound-token-without-re-binding-the-proof-key-jti-collision-and-ath-drift-in-oauth-2-1-agent-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-dpop-bound-token-without-re-binding-the-proof-key-jti-collision-and-ath-drift-in-oauth-2-1-agent-chains.warrant.json
# Markdown SHA-256:   125e46d3a0e5b330b791bb52389e99d6b95690c06a8584e8e8c512e324280e04
# Code AST SHA-256:   747273ea8041f59ac7d765e31b2ee152d9e0e55a68da7190e05c11f99c771339
# Verified Classes:   DPoPBindingError, DPoPProof, AccessToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import base64
import hashlib
import json
from dataclasses import dataclass


class DPoPBindingError(RuntimeError):
    """Raised when a delegated token's cnf.jkt or proof ath does not bind to the presenting agent's key."""


@dataclass
class DPoPProof:
    jkt: str          # thumbprint of the key that signed this proof
    ath: str          # base64url(sha256(access_token))
    jti: str          # unique per proof; RS replay cache key
    iat: int


@dataclass
class AccessToken:
    raw: str
    cnf_jkt: str      # thumbprint the issuer bound the token to
    audience: str


def b64url_sha256(s: str) -> str:
    return base64.urlsafe_b64encode(hashlib.sha256(s.encode()).digest()).rstrip(b"=").decode()


def preflight_binding_check(token: AccessToken, proof: DPoPProof, agent_key_thumbprint: str) -> None:
    """
    Invariant: token.cnf.jkt == proof.jkt == agent_key_thumbprint
               and proof.ath == sha256(token.raw)
    Runs before any network call so the agent never emits a proof the RS will reject
    for a reason the agent cannot disambiguate from the response.
    """
    expected_ath = b64url_sha256(token.raw)

    if token.cnf_jkt != proof.jkt:
        raise DPoPBindingError(
            f"cnf.jkt ({token.cnf_jkt}) != proof.jkt ({proof.jkt}): "
            "token was bound to a different key than the one signing this proof; "
            "re-exchange with a proof signed by the delegate's key, do not retry."
        )

    if proof.jkt != agent_key_thumbprint:
        raise DPoPBindingError(
            f"proof.jkt ({proof.jkt}) != agent key ({agent_key_thumbprint}): "
            "proof was signed by a key the agent does not hold; key lifecycle bug."
        )

    if proof.ath != expected_ath:
        raise DPoPBindingError(
            f"ath mismatch: proof.ath={proof.ath} expected={expected_ath}. "
            "Token was refreshed but proof was cached; mint fresh proof, keep token."
        )


def delegate_token(
    parent: AccessToken,
    delegate_key_thumbprint: str,
    exchange_fn,
    max_attempts: int = 2,
) -> AccessToken:
    """
    Exchange parent token for a child bound to the delegate's key.
    Refuses to propagate parent.cnf_jkt into the child (the observed failure).
    """
    last_err: Exception | None = None
    for attempt in range(1, max_attempts + 1):
        child = exchange_fn(parent=parent, bind_to_jkt=delegate_key_thumbprint)
        if child.cnf_jkt != delegate_key_thumbprint:
            last_err = DPoPBindingError(
                f"AS bound child to {child.cnf_jkt}, expected {delegate_key_thumbprint}; "
                "exchange request lacked a DPoP proof signed by the delegate."
            )
            continue
        return child
    raise DPoPBindingError(
        f"delegation failed after {max_attempts} attempts: {last_err}. "
        "Escalate to orchestrator; do not loop."
    )
