# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-peer-s-reputation-attestation-as-a-fresh-assertion-rather-than-a-settled-fact-when-federating-trust-across-org-boundari.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-peer-s-reputation-attestation-as-a-fresh-assertion-rather-than-a-settled-fact-when-federating-trust-across-org-boundari.warrant.json
# Markdown SHA-256:   580c52dd30e614631d2cba98a0da559e10a993462196232d588c7ee324a5ebcc
# Code AST SHA-256:   86aace095345c24a68d80ae8a3517de4c90677819dcf3e982717e0a8170d84bd
# Verified Classes:   AttestationAdmissionError, Manifest, Attestation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class AttestationAdmissionError(RuntimeError):
    """Raised when a federated reputation attestation fails admission."""
    pass


@dataclass(frozen=True)
class Manifest:
    org: str
    agent_id: str
    version: str
    manifest_hash: str


@dataclass(frozen=True)
class Attestation:
    issuer: str
    subject: str
    subject_manifest_hash: str
    score: float
    sample_size: int
    issued_at: float
    signature_valid: bool


MIN_SAMPLE_SIZE = 100
FRESHNESS_WINDOW_S = 24 * 3600


def admit_attestation(
    att: Attestation,
    subject_manifest: Manifest,
    issuer_manifest: Manifest,
    now: float,
    min_score_for_high_stakes: float = 0.90,
) -> float:
    """
    Admit or reject a cross-org reputation attestation for a delegation.

    Returns the effective (possibly discounted) score if admissible.
    Raises AttestationAdmissionError on any binding or validity failure.
    """
    if not att.signature_valid:
        raise AttestationAdmissionError(
            f"signature invalid for attestation {att.issuer}->{att.subject}; "
            "reject unconditionally"
        )

    if att.subject != subject_manifest.agent_id:
        raise AttestationAdmissionError(
            f"attestation subject {att.subject!r} does not match "
            f"manifest agent {subject_manifest.agent_id!r}"
        )

    # The load-bearing check: binding to the *current* subject manifest hash.
    if att.subject_manifest_hash != subject_manifest.manifest_hash:
        raise AttestationAdmissionError(
            f"manifest-hash mismatch: attestation bound to "
            f"{att.subject_manifest_hash[:12]}... but subject is now at "
            f"{subject_manifest.manifest_hash[:12]}... "
            f"(version {subject_manifest.version}); "
            "time freshness cannot mask manifest drift"
        )

    age = now - att.issued_at
    if age > FRESHNESS_WINDOW_S:
        raise AttestationAdmissionError(
            f"attestation age {age:.0f}s exceeds freshness window "
            f"{FRESHNESS_WINDOW_S}s"
        )
    if age < 0:
        raise AttestationAdmissionError(
            f"attestation issued_at is in the future by {-age:.0f}s; "
            "clock skew or forged timestamp"
        )

    if att.sample_size < MIN_SAMPLE_SIZE:
        # Soft failure: admit at a discounted score, requiring corroboration.
        discount = att.sample_size / MIN_SAMPLE_SIZE
        return att.score * discount

    if att.score < min_score_for_high_stakes:
        raise AttestationAdmissionError(
            f"score {att.score:.3f} below high-stakes threshold "
            f"{min_score_for_high_stakes:.3f}"
        )

    return att.score


def _h(s: str) -> str:
    return hashlib.sha256(s.encode()).hexdigest()


if __name__ == "__main__":
    v31 = Manifest("org-b", "worker-7", "v3.1", _h("worker-7:v3.1"))
    v40 = Manifest("org-b", "worker-7", "v4.0", _h("worker-7:v4.0"))
    issuer = Manifest("org-c", "audit-C", "v1.0", _h("audit-C:v1.0"))

    att = Attestation(
        issuer="audit-C",
        subject="worker-7",
        subject_manifest_hash=v31.manifest_hash,  # bound to v3.1
        score=0.94,
        sample_size=1200,
        issued_at=time.time() - 40 * 60,  # 40 minutes old: fresh by time
        signature_valid=True,
    )

    # Fresh subject at v3.1: admissible.
    print("v3.1 admission:", admit_attestation(att, v31, issuer, time.time()))

    # Subject bumped to v4.0: same attestation must be rejected despite freshness.
    try:
        admit_attestation(att, v40, issuer, time.time())
    except AttestationAdmissionError as e:
        print("v4.0 admission rejected:", e)
