# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-delegated-capability-token-s-scope-intersection-as-a-lattice-meet-rather-than-a-set-union-and-why-does-the.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-delegated-capability-token-s-scope-intersection-as-a-lattice-meet-rather-than-a-set-union-and-why-does-the.warrant.json
# Markdown SHA-256:   9d2c9f15170a3274a05dadd68faaf448e713896aa67ce5a274d76930256728f6
# Code AST SHA-256:   846f1bfe7c7f7fd346d052cdd5f4728b368da25bdda251ee0fa1bee7fda874af
# Verified Classes:   ScopeMeetViolation, Triple, Credential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ScopeMeetViolation(RuntimeError):
    """Raised when a delegated credential's declared scope is not provably
    a subset of the parent's live effective scope (lattice meet failed)."""


@dataclass(frozen=True)
class Triple:
    tenant: str
    action: str
    resource: str
    predicate: str  # e.g. "region:us"; part of the meet, not decoration


@dataclass(frozen=True)
class Credential:
    declared_scope: frozenset[Triple]
    parent_scope_digest: Optional[str]  # hash of parent effective scope at issuance


def digest(scope: frozenset[Triple]) -> str:
    canon = "|".join(sorted(f"{t.tenant}/{t.action}/{t.resource}/{t.predicate}" for t in scope))
    return hashlib.sha256(canon.encode()).hexdigest()


def effective_scope(
    cred: Credential,
    parent_live_scope: Optional[frozenset[Triple]],
) -> frozenset[Triple]:
    """Compute the lattice meet of declared scope with parent's live scope.

    Fails closed when the parent scope cannot be obtained and the digest
    does not prove the declared set was already a subset at issuance.
    """
    if parent_live_scope is None:
        if cred.parent_scope_digest is None:
            raise ScopeMeetViolation(
                "parent scope unreachable and no committed digest; "
                "declared scope is an upper bound, refusing to authorize"
            )
        # Digest present but parent unreachable: we cannot recompute the
        # parent's *current* scope, so we cannot bound drift. Fail closed.
        raise ScopeMeetViolation(
            "parent scope unreachable; cannot recompute meet against live scope"
        )

    live_digest = digest(parent_live_scope)
    if cred.parent_scope_digest is not None and cred.parent_scope_digest == live_digest:
        # Declared set was a subset at issuance and parent has not drifted.
        meet = cred.declared_scope & parent_live_scope
        if meet != cred.declared_scope:
            # Digest matched but declared exceeds live: digest was stale/wrong.
            raise ScopeMeetViolation(
                "declared scope exceeds parent live scope despite digest match"
            )
        return meet

    # Digest absent or drifted: declared set is only an upper bound.
    meet = cred.declared_scope & parent_live_scope
    if meet != cred.declared_scope:
        over = cred.declared_scope - parent_live_scope
        raise ScopeMeetViolation(
            f"delegation over-declares {len(over)} triple(s) not in parent "
            f"live scope, e.g. {sorted(over)[0]!r}; meet is strictly smaller"
        )
    return meet


def authorize(
    cred: Credential,
    parent_live_scope: Optional[frozenset[Triple]],
    request: Triple,
) -> bool:
    meet = effective_scope(cred, parent_live_scope)
    if request not in meet:
        raise ScopeMeetViolation(
            f"request {request!r} not in effective (meet) scope; "
            f"existence-in-declared is not sufficient"
        )
    return True
