# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-memory-write-whose-namespace-scope-outlives-the-writing-agent-s-own-ttl.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-memory-write-whose-namespace-scope-outlives-the-writing-agent-s-own-ttl.warrant.json
# Markdown SHA-256:   415537a2391c67a26a7d2819d8fbe4920c41562bf3a2ff7a0d8577e7d1fae691
# Code AST SHA-256:   b45f310510c8bb20f8bbdbc8d5f342797065c9fec1f5236c33887e5caece5ff2
# Verified Classes:   AuthorityOrphaningWrite, Lease, WriteRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass


class AuthorityOrphaningWrite(RuntimeError):
    """Raised when a memory write's TTL would outlive the writer's lease
    without a renewal principal or an explicit provisional downgrade."""
    pass


@dataclass(frozen=True)
class Lease:
    principal: str
    lease_id: str
    expires_at: float  # epoch seconds


@dataclass(frozen=True)
class WriteRequest:
    namespace: str
    key: str
    value: str
    ttl_s: int
    renewal_principal: str | None = None
    allow_provisional: bool = False


def admit_write(
    req: WriteRequest,
    lease: Lease,
    namespace_max_ttl_s: int,
    now: float | None = None,
) -> dict:
    """Validate a scoped memory write against the writer's lease horizon.

    Returns the stamped entry to persist. Raises AuthorityOrphaningWrite
    when the entry would survive its warrant with no re-warranting path.
    """
    now = time.time() if now is None else now
    remaining = lease.expires_at - now
    if remaining <= 0:
        raise AuthorityOrphaningWrite(
            f"lease {lease.lease_id} for {lease.principal} already expired"
        )

    effective_ttl = min(req.ttl_s, namespace_max_ttl_s)

    # Path 1: entry dies with or before the warrant. Safe.
    if effective_ttl <= remaining:
        return {
            "namespace": req.namespace,
            "key": req.key,
            "value": req.value,
            "expires_at": now + effective_ttl,
            "authority": "verified",
            "writer": lease.principal,
            "lease_id": lease.lease_id,
        }

    # Path 2: outlives the lease but a renewal principal carries it forward.
    if req.renewal_principal is not None:
        return {
            "namespace": req.namespace,
            "key": req.key,
            "value": req.value,
            "expires_at": now + effective_ttl,
            "authority": "delegated",
            "writer": lease.principal,
            "lease_id": lease.lease_id,
            "renewal_principal": req.renewal_principal,
            "demote_at": lease.expires_at,
        }

    # Path 3: explicit provisional downgrade — readable as hypothesis only.
    if req.allow_provisional:
        return {
            "namespace": req.namespace,
            "key": req.key,
            "value": req.value,
            "expires_at": now + effective_ttl,
            "authority": "provisional",
            "writer": lease.principal,
            "lease_id": lease.lease_id,
            "demote_at": lease.expires_at,
        }

    # Path 4: orphan-in-waiting. Refuse. Do not silently clamp.
    raise AuthorityOrphaningWrite(
        f"write ttl={effective_ttl}s exceeds lease remainder={remaining:.0f}s "
        f"for principal={lease.principal} namespace={req.namespace}; "
        f"supply renewal_principal, shorten ttl_s to <= {int(remaining)}s, "
        f"or set allow_provisional=True"
    )
