# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-mint-an-aaif-attestation-because-its-own-credential-chain-is-mid-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-mint-an-aaif-attestation-because-its-own-credential-chain-is-mid-rotation.warrant.json
# Markdown SHA-256:   db99ae5e5555df7fe8c44fd523a7cf72babd419cb713ececed11e8ffbd3f965c
# Code AST SHA-256:   e176f3e9d8c4202c4291038b5edaff56cad9496bb16b57ca3129fe5734c73124
# Verified Classes:   RotationHoldViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class RotationHoldViolation(RuntimeError):
    """Raised when an issuer attempts to mint during a rotation overlap
    without a satisfiable verifier-floor predicate."""
    pass


def select_signing_key(keys, verifier_floor, now, skew_tolerance_s=2.0):
    """
    keys: list of dicts with 'kid', 'published_at', 'not_after', 'signing'
    verifier_floor: dict with 'min_refresh_epoch' (float epoch seconds) or None
    Returns (kid, None) if safe to mint, else (None, hold_until_epoch).
    """
    if verifier_floor is None or verifier_floor.get("min_refresh_epoch") is None:
        # Cannot evaluate invariant; fail closed with conservative default.
        drain = 300.0
        candidates = [k for k in keys if k.get("signing")]
        if not candidates:
            raise RotationHoldViolation("no signing key available and no verifier floor")
        return None, now + drain

    floor = verifier_floor["min_refresh_epoch"]
    safe = [
        k for k in keys
        if k.get("signing")
        and k["published_at"] <= floor
        and k["not_after"] > now + skew_tolerance_s
    ]
    if safe:
        # Prefer the newest key that is already visible to the verifier floor.
        safe.sort(key=lambda k: k["published_at"], reverse=True)
        return safe[0]["kid"], None

    # No key satisfies atomicity; compute earliest safe mint time.
    future = [
        k for k in keys
        if k.get("signing") and k["not_after"] > now + skew_tolerance_s
    ]
    if not future:
        raise RotationHoldViolation(
            "issuer has no key valid past now; must re-parent to peer issuer"
        )
    hold_until = min(k["published_at"] for k in future)
    if hold_until <= now:
        # Keys exist but none visible to floor and none future-dated: registry
        # lag or clock skew. Refuse rather than guess.
        raise RotationHoldViolation(
            f"key visibility floor {floor} exceeds all published_at; "
            f"clock skew or registry lag suspected"
        )
    return None, hold_until


def mint_attestation(issuer, subject, scope, keys, verifier_floor, now):
    kid, hold_until = select_signing_key(keys, verifier_floor, now)
    if kid is None:
        return {
            "status": "ROTATION_HOLD",
            "retry_after": hold_until,
            "reason": "issuer credential mid-rotation; verifier floor not yet satisfied",
        }
    return issuer.sign(subject=subject, scope=scope, kid=kid, issued_at=now)
