# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-audit-trail-gap-as-a-routing-failure-rather-than-a-logging-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-audit-trail-gap-as-a-routing-failure-rather-than-a-logging-failure.warrant.json
# Markdown SHA-256:   ecafb1d9d706582998c95944b1373f0147777a05046456ac5dc45aadfbc236ef
# Code AST SHA-256:   f4dee5dd6f8f33b7876f1b4732a7d18dd801861bb6424a0f6f7544f11d66e6d6
# Verified Classes:   FederatedAuditGapError, MessageState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class FederatedAuditGapError(RuntimeError):
    """Raised when a FORWARDED message lacks a crash-durable intent record,
    making the audit gap unrecoverable and the message potentially ORPHANED_ACTION."""


class MessageState:
    DECIDED_ALLOW = "DECIDED_ALLOW"
    FORWARDED = "FORWARDED"
    ATTESTED = "ATTESTED"
    ORPHANED_ACTION = "ORPHANED_ACTION"
    BLOCKED = "BLOCKED"


def forward_with_attestation_intent(
    decision_id: str,
    recipient_org: str,
    local_wal,
    ledger_client,
    forward_fn,
):
    """Forward a cross-org message only if an intent-to-attest record is durable.

    The intent record is a local, crash-survivable write keyed by decision_id.
    It is the promise that lets a restarted PEP re-drive the attestation to the
    federation ledger. Without it, a crash between forward and attest yields an
    unrecoverable audit gap across orgs.
    """
    # 1. Write the intent record durably BEFORE forwarding.
    try:
        local_wal.append(
            {"decision_id": decision_id, "recipient_org": recipient_org,
             "state": MessageState.DECIDED_ALLOW}
        )
        local_wal.fsync()
    except OSError as exc:
        # Cannot promise attestation -> must not forward cross-org.
        raise FederatedAuditGapError(
            f"intent record not durable for decision {decision_id} "
            f"to {recipient_org}; refusing cross-org forward: {exc}"
        ) from exc

    # 2. Forward. State is now FORWARDED but not yet ATTESTED.
    forward_fn(decision_id)
    local_wal.append({"decision_id": decision_id, "state": MessageState.FORWARDED})

    # 3. Async attestation is re-drivable from the intent record on restart.
    try:
        ledger_client.attest(decision_id, recipient_org)
        local_wal.append({"decision_id": decision_id, "state": MessageState.ATTESTED})
    except Exception:
        # Not fatal: intent record survives; reconciliation will re-drive.
        # But if the intent record itself is gone, this is unrecoverable.
        if not local_wal.contains(decision_id):
            raise FederatedAuditGapError(
                f"lost intent record for forwarded decision {decision_id}; "
                f"possible ORPHANED_ACTION at {recipient_org}"
            )
    return MessageState.FORWARDED


def reconcile_on_restart(local_wal, ledger_client, execution_log):
    """Re-drive attestations and flag orphaned actions after a PEP restart."""
    for intent in local_wal.iter_pending():
        decision_id = intent["decision_id"]
        if not ledger_client.has_attestation(decision_id):
            ledger_client.attest(decision_id, intent["recipient_org"])

    for exec_entry in execution_log.iter_since(local_wal.last_checkpoint()):
        if not local_wal.contains(exec_entry["decision_id"]):
            raise FederatedAuditGapError(
                f"execution {exec_entry['id']} at {exec_entry['org']} has no "
                f"matching intent record for decision {exec_entry['decision_id']}; "
                f"ORPHANED_ACTION requires federation-level reconciliation"
            )
