"""Authorization checks for a trusted, already authenticated runtime context."""
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from decimal import Decimal


@dataclass(frozen=True)
class Grant:
    principal: str
    agent: str
    resources: frozenset[str]
    actions: frozenset[str]
    expires_at: datetime
    revoked: bool = False


def authorize(grant: Grant, *, principal: str, agent: str, resource: str,
              action: str, now: datetime, spent: Decimal,
              budget: Decimal, tool_calls: int) -> None:
    """Raise on denial. The caller supplies verified identity and usage."""
    checks = (
        not grant.revoked,
        now < grant.expires_at,
        principal == grant.principal,
        agent == grant.agent,
        resource in grant.resources,
        action in grant.actions,
        Decimal("0") <= spent < budget,
        0 <= tool_calls < 100,
    )
    if not all(checks):
        raise PermissionError("Action is outside the current authority or limits")


if __name__ == "__main__":
    now = datetime.now(timezone.utc)
    grant = Grant(
        principal="alice", agent="incident-investigator",
        resources=frozenset({"service-a"}),
        actions=frozenset({"logs.search", "deployments.read"}),
        expires_at=now + timedelta(hours=2),
    )
    context = dict(principal="alice", agent="incident-investigator",
                   resource="service-a", action="logs.search", now=now,
                   spent=Decimal("0.50"), budget=Decimal("5.00"), tool_calls=3)
    authorize(grant, **context)
    print("ALLOW: logs.search on service-a")
    try:
        authorize(grant, **{**context, "action": "deployments.rollback"})
    except PermissionError:
        print("DENY: deployments.rollback on service-a")
    else:
        raise AssertionError("An unauthorized action was allowed")
