# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-anchor-its-tamper-evident-audit-chain-when-the-signing-key-rotates-mid-handoff-across-organizations.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-anchor-its-tamper-evident-audit-chain-when-the-signing-key-rotates-mid-handoff-across-organizations.warrant.json
# Markdown SHA-256:   b5f3245999cd8d1bdecb78bf9c97ac5c967bf7e67e750189e4644f529837c90f
# Code AST SHA-256:   55cd0839c443bbe52933ed5f26e1dd5236683ee5b5ecfe296c9326d2d100b7e7
# Verified Classes:   SeamAnchorError, AuditRecord, HandoffEnvelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Optional


class SeamAnchorError(RuntimeError):
    """Raised when a cross-org audit seam cannot be anchored verifiably."""
    pass


@dataclass
class AuditRecord:
    prev_hash: str
    payload: str
    signer_key_id: str
    signer_epoch: int
    written_at: float
    record_hash: str = field(init=False)

    def __post_init__(self):
        self.record_hash = hashlib.sha256(
            f"{self.prev_hash}|{self.payload}|{self.signer_key_id}|{self.signer_epoch}".encode()
        ).hexdigest()


@dataclass
class HandoffEnvelope:
    terminal_hash: str
    attached_key_id: str          # key read at serialization time (the bug)
    attached_epoch: int
    serialized_at: float
    accept_rotated_within: Optional[float] = None


def build_envelope(segment: list[AuditRecord], current_key_id: str,
                   current_epoch: int, now: float) -> HandoffEnvelope:
    # BUG: attaches the *current* keyring, not the terminal record's signer.
    return HandoffEnvelope(
        terminal_hash=segment[-1].record_hash,
        attached_key_id=current_key_id,
        attached_epoch=current_epoch,
        serialized_at=now,
    )


def verify_seam(segment: list[AuditRecord], env: HandoffEnvelope,
                now: float, key_verifiable_until: float) -> None:
    terminal = segment[-1]
    if env.attached_key_id != terminal.signer_key_id:
        # Correct behavior: hard-fail. Do NOT fall back to hash-only.
        raise SeamAnchorError(
            f"seam key mismatch: envelope attached {env.attached_key_id} "
            f"(epoch {env.attached_epoch}) but terminal record signed by "
            f"{terminal.signer_key_id} (epoch {terminal.signer_epoch}); "
            f"cannot distinguish rotation from substitution at audit time"
        )
    if now > key_verifiable_until and terminal.signer_epoch != env.attached_epoch:
        raise SeamAnchorError(
            f"seam unverifiable after key expiry: signer {terminal.signer_key_id} "
            f"expired at {key_verifiable_until}, audit at {now}"
        )


def extend_chain(segment: list[AuditRecord], env: HandoffEnvelope,
                 now: float, key_verifiable_until: float) -> AuditRecord:
    verify_seam(segment, env, now, key_verifiable_until)
    terminal = segment[-1]
    return AuditRecord(
        prev_hash=terminal.record_hash,
        payload="<org B first record>",
        signer_key_id="key_B_v1",
        signer_epoch=1,
        written_at=now,
    )


# Reproduction of the observed trace.
if __name__ == "__main__":
    T = 1_700_000_000.0
    seg = [
        AuditRecord("genesis", "plan step 1", "key_A_v7", 7, T + 23 * 3600 + 58 * 60),
    ]
    env = build_envelope(seg, current_key_id="key_A_v8", current_epoch=8,
                         now=T + 24 * 3600 + 2 * 60)
    # At receive time, v7 is still within overlap; verifier catches the mismatch.
    try:
        extend_chain(seg, env, now=T + 24 * 3600 + 2 * 60,
                     key_verifiable_until=T + 24 * 3600 + 59 * 60)
    except SeamAnchorError as e:
        print(f"rejected at receive: {e}")
    # At audit time, v7 has expired; without the hard-fail the seam is lost.
