# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-redaction-as-a-replay-integrity-invariant-rather-than-a-post-hoc-sanitizer.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-redaction-as-a-replay-integrity-invariant-rather-than-a-post-hoc-sanitizer.warrant.json
# Markdown SHA-256:   255e70087ec5fa621461562f8c0017a73e45894c473dc71a25cb559055c2d8fe
# Code AST SHA-256:   916c578fa4da07391dcf4c0b87153ce97257b2f3090039cf607400fb975729f9
# Verified Classes:   RedactionIntegrityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import base64
import json
import re
from typing import Any, Callable


class RedactionIntegrityError(RuntimeError):
    """Raised when redaction has broken the grammar a replay parser depends on."""


# Parsers a replay engine may apply to a redacted span. Each returns True if
# the value is still well-formed under that grammar.
PARSERS: dict[str, Callable[[str], bool]] = {
    "json": lambda v: _try(lambda: json.loads(v)),
    "base64": lambda v: _try(lambda: base64.b64decode(v, validate=True)),
    "jwt": lambda v: _try(lambda: _check_jwt(v)),
}


def _try(fn: Callable[[], Any]) -> bool:
    try:
        fn()
        return True
    except Exception:
        return False


def _check_jwt(v: str) -> None:
    parts = v.split(".")
    if len(parts) != 3:
        raise ValueError("not a JWT")
    for p in parts[:2]:
        base64.urlsafe_b64decode(p + "=" * (-len(p) % 4))


def redact_span(value: str, parser: str, marker: str = "[REDACTED]") -> str:
    """Redact a span while preserving the grammar of its declared parser."""
    if parser not in PARSERS:
        # Opaque consumer: free-text substitution is safe.
        return marker
    if parser == "json":
        # Preserve JSON type by substituting a string sentinel, not raw marker
        # into a numeric/boolean slot. Caller must have validated type first.
        return json.dumps(marker)
    if parser == "base64":
        # Keep valid base64 of identical length so downstream length checks hold.
        raw = marker.encode()
        return base64.b64encode(raw).decode()
    if parser == "jwt":
        # Preserve three-segment shape with non-privileged canary payloads.
        seg = base64.urlsafe_b64encode(b'{"canary":true}').decode().rstrip("=")
        return f"{seg}.{seg}.{seg}"
    return marker


def validate_replay_span(value: str, parser: str, path: str) -> None:
    """Fail closed if a redacted span no longer parses under its consumer grammar."""
    if parser not in PARSERS:
        return
    if not PARSERS[parser](value):
        raise RedactionIntegrityError(
            f"redaction broke grammar at {path!r}: parser={parser!r} "
            f"cannot parse redacted value; replay would diverge from a "
            f"redaction artifact, not the system under test"
        )


def build_replay_trace(raw_args: dict, redactions: list[dict]) -> dict:
    """Apply redactions and validate each redacted span against its parser."""
    trace = json.loads(json.dumps(raw_args))  # deep copy
    for r in redactions:
        path, parser = r["path"], r["parser"]
        node = trace
        keys = path.split(".")
        for k in keys[:-1]:
            node = node[int(k)] if k.isdigit() else node[k]
        leaf = keys[-1]
        node[leaf] = redact_span(str(node[leaf]), parser)
        validate_replay_span(node[leaf], parser, path)
    return trace


if __name__ == "__main__":
    raw = {"headers": {"Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJqYW5lIn0.sig"}}
    # Correct: treat the whole header as opaque free text, not a JWT slot.
    ok = build_replay_trace(raw, [{"path": "headers.Authorization", "parser": "opaque"}])
    # Incorrect: declare the header as a JWT parser while redacting to a marker.
    try:
        bad = build_replay_trace(
            raw, [{"path": "headers.Authorization", "parser": "jwt"}]
        )
        # If redact_span produced a valid canary JWT, this succeeds; if a naive
        # marker was injected, validation raises.
        validate_replay_span(bad["headers"]["Authorization"], "jwt", "headers.Authorization")
    except RedactionIntegrityError as e:
        raise RedactionIntegrityError(
            f"trace redaction violated replay invariant: {e}"
        ) from e
