# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-the-moment-its-parent-token-refreshes-the-credential-chain-continuity-invariant-in-aaif-short-lived-scop.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-the-moment-its-parent-token-refreshes-the-credential-chain-continuity-invariant-in-aaif-short-lived-scop.warrant.json
# Markdown SHA-256:   f2bb7ffca71d142c6bc2e80d95073d35cfe16885810156c4aa397687bea78a21
# Code AST SHA-256:   ddaa312ed3c0e489d97cd3e5e1f815b66e814c9e6b5751bc748e592694a0913a
# Verified Classes:   LineageBrokenError, Token, LiveRootRegistry, LeafCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class LineageBrokenError(RuntimeError):
    """Raised when a delegated credential's root is no longer live in the registry."""
    pass


@dataclass
class Token:
    jti: str
    parent_jti: Optional[str]
    parent_exp: Optional[float]
    exp: float
    scope: str
    signature_ok: bool = True


@dataclass
class LiveRootRegistry:
    live: dict = field(default_factory=dict)  # jti -> exp

    def register(self, tok: Token) -> None:
        self.live[tok.jti] = tok.exp

    def evict(self, jti: str) -> None:
        self.live.pop(jti, None)

    def is_live(self, jti: str, now: float) -> bool:
        exp = self.live.get(jti)
        return exp is not None and now < exp


@dataclass
class LeafCache:
    # Correct keying: (scope, audience, parent_jti). The bug was omitting parent_jti.
    entries: dict = field(default_factory=dict)

    def key(self, tok: Token, audience: str) -> tuple:
        return (tok.scope, audience, tok.parent_jti)

    def get(self, tok: Token, audience: str, now: float) -> Optional[Token]:
        cached = self.entries.get(self.key(tok, audience))
        if cached is None:
            return None
        # Reuse only while the recorded parent is still within its own window.
        if cached.parent_exp is not None and now >= cached.parent_exp:
            # Not a hit: this is a re-derivation trigger, not a cached authority.
            self.entries.pop(self.key(tok, audience), None)
            return None
        return cached

    def put(self, tok: Token, audience: str) -> None:
        self.entries[self.key(tok, audience)] = tok


def verify_leaf(
    leaf: Token,
    registry: LiveRootRegistry,
    cache: LeafCache,
    audience: str,
    now: float,
) -> Token:
    if not leaf.signature_ok:
        raise LineageBrokenError(f"leaf {leaf.jti} signature invalid")

    if now >= leaf.exp:
        # Distinct reason: expired leaf is retryable after re-mint.
        raise LineageBrokenError(f"leaf {leaf.jti} expired at {leaf.exp}")

    if leaf.parent_jti is None:
        # A root presented as a leaf: must itself be live.
        if not registry.is_live(leaf.jti, now):
            raise LineageBrokenError(f"root {leaf.jti} not live at {now}")
        return leaf

    # Lineage-liveness: the recorded parent must still be live in the registry.
    if not registry.is_live(leaf.parent_jti, now):
        # This is the exact failure from the trace: root refreshed, old jti evicted,
        # child's leaf still unexpired but lineage is dead.
        raise LineageBrokenError(
            f"lineage broken: parent {leaf.parent_jti} evicted before leaf {leaf.jti} "
            f"(parent_exp={leaf.parent_exp}, now={now}); re-derive up the chain"
        )

    cached = cache.get(leaf, audience, now)
    if cached is not None:
        return cached

    cache.put(leaf, audience)
    return leaf


def refresh_root(
    old_root: Token,
    new_root: Token,
    registry: LiveRootRegistry,
    descendants: list,
    now: float,
) -> None:
    # Correct refresh: re-derive descendants BEFORE evicting the old root,
    # so no window exists where a live leaf points at a dead lineage.
    for d in descendants:
        if d.parent_jti == old_root.jti:
            d.parent_jti = new_root.jti
            d.parent_exp = new_root.exp
    registry.register(new_root)
    registry.evict(old_root.jti)
