# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-divergent-audit-trail-sequence-numbers-before-accepting-a-federated-capability-grant.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-divergent-audit-trail-sequence-numbers-before-accepting-a-federated-capability-grant.warrant.json
# Markdown SHA-256:   68d6cc538d99eaeaf1f26e7b2bb94ced3471a161bf995dce230bbbdfd4061bbd
# Code AST SHA-256:   a94531e959120f9508d701d2f300ec0712f936bb5be5b9633437e2d9f1c61df9
# Verified Classes:   AuditReconciliationError, GrantState, LogEntry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class AuditReconciliationError(RuntimeError):
    """Raised when a federated warrant cannot be classified from the two audit logs."""


class GrantState(Enum):
    VALID = "valid"
    PROVISIONAL = "provisional"
    REVOKED = "revoked"


@dataclass(frozen=True)
class LogEntry:
    org: str
    seq: int
    warrant_id: str
    kind: str            # offer | counter | accept | issue | ack | suppressed-ack
    terminal: bool = False
    sub_seq: int = 0     # per-warrant counter, NOT per-connection


def reconcile_warrant(warrant_id: str, alpha: list[LogEntry], beta: list[LogEntry]) -> GrantState:
    a = [e for e in alpha if e.warrant_id == warrant_id]
    b = [e for e in beta if e.warrant_id == warrant_id]
    if not a or not b:
        raise AuditReconciliationError(
            f"warrant {warrant_id} missing from one log; cannot reconcile"
        )

    # Per-warrant sub-sequence must be dense and non-repeating within each log.
    for side, entries in (("alpha", a), ("beta", b)):
        subs = sorted(e.sub_seq for e in entries)
        if subs != list(range(len(subs))):
            raise AuditReconciliationError(
                f"{side} log for {warrant_id} has non-dense sub_seq {subs}; "
                "sequence divergence is unprovable"
            )

    issues = [e for e in a + b if e.kind == "issue"]
    acks = [e for e in a + b if e.kind in ("ack", "suppressed-ack")]
    if not issues:
        raise AuditReconciliationError(f"no issue record for {warrant_id}")

    terminal_issues = [e for e in issues if e.terminal]
    if len(terminal_issues) != 1:
        # Zero terminal issues => retried non-terminal only; >1 => re-issue ambiguity.
        raise AuditReconciliationError(
            f"{warrant_id} has {len(terminal_issues)} terminal issue records; "
            "expected exactly 1"
        )

    issue_sub = terminal_issues[0].sub_seq
    # Every recv-issue sub_seq must be paired with an ack of the same sub_seq,
    # OR carry an explicit suppressed-ack marker at that position.
    paired = {e.sub_seq for e in acks}
    unpaired = [e for e in issues if e.sub_seq not in paired and e.sub_seq != issue_sub]
    if unpaired:
        # Duplicate recv-issue with no ack and no suppression marker.
        # Unprovable, but not forged: downgrade, do not revoke.
        return GrantState.PROVISIONAL

    # A recv-issue on one side with no send-issue on the other is the forgery signature.
    send_issue_orgs = {e.org for e in issues if e.kind == "issue" and e.terminal}
    if len(send_issue_orgs) != 1:
        raise AuditReconciliationError(
            f"{warrant_id} terminal issue claimed by {send_issue_orgs}; "
            "cannot determine issuer"
        )

    if any(e.kind == "issue" and not e.terminal and e.sub_seq == issue_sub for e in issues):
        return GrantState.PROVISIONAL

    return GrantState.VALID
