# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-quorum-certificate-whose-trust-slices-are-non-overlapping-across-federated-agent-organizations.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-quorum-certificate-whose-trust-slices-are-non-overlapping-across-federated-agent-organizations.warrant.json
# Markdown SHA-256:   1371e7ffda0370f209a9482ac006618f41f1ef2dff52a52421ea3f69dd704501
# Code AST SHA-256:   a1c25da5299a2ad5bdf2e71d76c91a4d922363cc1b35d1562130e8687d15c591
# Verified Classes:   QuorumIntersectionViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class QuorumIntersectionViolation(RuntimeError):
    """Raised when two quorum certificates cannot be safely merged because
    their realized signer sets share no mutually-trusted witness."""
    pass


def merge_quorum_certificates(
    local_qc: dict,
    remote_qc: dict,
    local_trust: set,
    remote_trust: set,
) -> dict:
    """
    local_qc / remote_qc: {"state": str, "seq": int, "signers": set[str]}
    local_trust / remote_trust: declared trusted node ids per issuer org.

    Returns the merged QC only if a mutually-trusted shared witness exists.
    """
    local_signers = set(local_qc["signers"])
    remote_signers = set(remote_qc["signers"])

    shared = local_signers & remote_signers
    if not shared:
        # Case C: disjoint realized quorums. The federation's trust topology
        # did not enforce intersection on this execution path. Not a tie.
        raise QuorumIntersectionViolation(
            f"No shared signer between local QC (state={local_qc['state']!r}) "
            f"and remote QC (state={remote_qc['state']!r}); quorums are "
            f"incomparable. Refusing to merge or vote."
        )

    # Case B guard: a shared signer trusted by neither issuer is a Byzantine
    # bridge, not a safety anchor.
    witnesses = shared & local_trust & remote_trust
    if not witnesses:
        raise QuorumIntersectionViolation(
            f"Shared signers {sorted(shared)} are not mutually trusted by both "
            f"issuers; treating as adversarial bridge. Discarding both QCs."
        )

    # Case A: safe to order by the witness-attested sequence number.
    witness = sorted(witnesses)[0]
    winner = local_qc if local_qc["seq"] >= remote_qc["seq"] else remote_qc
    return {
        "state": winner["state"],
        "seq": winner["seq"],
        "witness": witness,
        "merged_signers": local_signers | remote_signers,
    }
