# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-lost-oauth-2-1-resource-server-binding-across-an-mcp-streamable-http-chunk-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-lost-oauth-2-1-resource-server-binding-across-an-mcp-streamable-http-chunk-boundary.warrant.json
# Markdown SHA-256:   1cdc81b5758cfc07dac129ad67565023214432c3dd21bb525a0ccc6f89eb7f09
# Code AST SHA-256:   b5697966991d71d50c22701e0ca284babd899870cb8a7876cb411b65fec4a25b
# Verified Classes:   BindingLifetimeViolation, StreamBinding
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class BindingLifetimeViolation(RuntimeError):
    """Raised when an MCP stream frame is emitted under a binding whose
    validity window does not cover the frame's emission time, or when a
    frame is attributed to a principal/resource pair other than the one
    that opened the stream."""


@dataclass(frozen=True)
class StreamBinding:
    principal: str
    resource: str
    token_exp: float          # absolute epoch seconds
    opened_at: float
    max_stream_age: float = 300.0
    revalidate_interval: float = 30.0

    def valid_at(self, now: float) -> bool:
        return (
            now < self.token_exp
            and (now - self.opened_at) < self.max_stream_age
        )


def emit_frame(
    binding: StreamBinding,
    frame_principal: str,
    frame_resource: str,
    now: float | None = None,
    last_revalidate: float | None = None,
) -> dict:
    now = time.time() if now is None else now

    if frame_principal != binding.principal or frame_resource != binding.resource:
        raise BindingLifetimeViolation(
            f"frame attributed to ({frame_principal}, {frame_resource}) "
            f"but stream opened under ({binding.principal}, {binding.resource}); "
            f"connection reuse across bindings detected"
        )

    if not binding.valid_at(now):
        raise BindingLifetimeViolation(
            f"frame emitted at t={now:.0f} outside binding window "
            f"[{binding.opened_at:.0f}, {min(binding.token_exp, binding.opened_at + binding.max_stream_age):.0f}]"
        )

    if last_revalidate is not None and (now - last_revalidate) > binding.revalidate_interval:
        raise BindingLifetimeViolation(
            f"no revalidation for {(now - last_revalidate):.0f}s "
            f"(limit {binding.revalidate_interval:.0f}s); binding may be stale"
        )

    return {
        "event": "message",
        "principal": binding.principal,
        "resource": binding.resource,
        "emitted_at": now,
        "remaining_token_ttl": binding.token_exp - now,
    }
