# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-inherit-a-federated-audit-epoch-across-a-cross-org-rebase-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-inherit-a-federated-audit-epoch-across-a-cross-org-rebase-boundary.warrant.json
# Markdown SHA-256:   279e00ab777a4e7e6b39cb78dd515bf2169b91abe42552064b246cb4f4cac296
# Code AST SHA-256:   a7e330b788cf7bd1acd480fc72329c39003cef7e2aa8f644639b2b202d94715d
# Verified Classes:   FederatedEpochBoundaryError, EpochToken, BoundaryContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class FederatedEpochBoundaryError(RuntimeError):
    """Raised when an instance attempts to forward an inherited audit epoch
    across an org boundary without re-minting it as a composed-path token."""


@dataclass(frozen=True)
class EpochToken:
    org: str
    epoch_id: str
    subject_instance: str
    composed_path: tuple  # (origin_org, ..., destination_org)
    parent: Optional["EpochToken"] = None

    def digest(self) -> str:
        h = hashlib.sha256()
        h.update(self.org.encode())
        h.update(b"|")
        h.update(self.epoch_id.encode())
        h.update(b"|")
        h.update(self.subject_instance.encode())
        h.update(b"|")
        h.update("->".join(self.composed_path).encode())
        if self.parent is not None:
            h.update(b"|")
            h.update(self.parent.digest().encode())
        return h.hexdigest()


@dataclass
class BoundaryContext:
    destination_org: str
    destination_signer_available: bool
    replay_guard_keys_on_composed_hash: bool
    dedup_window_seen: set = field(default_factory=set)


def transfer_epoch(
    inherited: EpochToken,
    ctx: BoundaryContext,
    new_epoch_id: str,
) -> EpochToken:
    """
    Re-mint an inherited epoch as a composed-path token at the boundary.
    Refuses to forward if the destination cannot mint or cannot key the
    replay guard on the composed hash.
    """
    if inherited.org == ctx.destination_org:
        # Not a boundary crossing; no re-mint required.
        return inherited

    if not ctx.destination_signer_available:
        raise FederatedEpochBoundaryError(
            f"destination org {ctx.destination_org!r} cannot mint a composed "
            f"epoch; refusing to forward inherited epoch "
            f"{inherited.org}:{inherited.epoch_id} from "
            f"{inherited.subject_instance!r}"
        )

    if not ctx.replay_guard_keys_on_composed_hash:
        raise FederatedEpochBoundaryError(
            "destination replay guard keys on (origin_org, epoch_id); "
            "inherited epoch would collide with prior instances from "
            f"{inherited.org!r}"
        )

    composed = inherited.composed_path + (ctx.destination_org,)
    minted = EpochToken(
        org=ctx.destination_org,
        epoch_id=new_epoch_id,
        subject_instance=inherited.subject_instance,
        composed_path=composed,
        parent=inherited,
    )

    key = minted.digest()
    if key in ctx.dedup_window_seen:
        raise FederatedEpochBoundaryError(
            f"composed-path token {key[:16]}… already observed in dedup "
            f"window at {ctx.destination_org!r}; possible replay"
        )

    ctx.dedup_window_seen.add(key)
    return minted
