"""
Streaming egress governance: buffer assistant chunks, scan once at message boundary.

Guard Dog must scan the **complete** assistant message for egress leaks (API keys,
system prompt fragments). Scanning individual SSE chunks causes false negatives
when tokens split across chunk boundaries.

For HTTP-boundary enforcement (no manual buffering), see
`asgi_egress_enforcement.py` in this directory — the library's
`EgressResponseMiddleware` wraps the ASGI send channel directly.

See documentation.html#gateway-proxy on the Vatrion website for gateway setup.

Prerequisites:
  Install the supplied Guard Dog wheel; see README.txt.

Run:
  python samples/integrations/streaming_egress.py
"""
from __future__ import annotations

import os
import sys

_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
if _ROOT not in sys.path:
    sys.path.insert(0, _ROOT)

from guard_dog.scanner import ScanConfig
from guard_dog.streaming import StreamingTextAccumulator, scan_assistant_output


def simulate_stream(chunks: list[str]) -> str:
    """Simulate an LLM streaming response; return full text."""
    acc = StreamingTextAccumulator()
    for chunk in chunks:
        acc.append(chunk)
    return acc.get_text()


def scan_completed_message(full_text: str) -> None:
    result = scan_assistant_output(full_text, base_config=ScanConfig())
    status = "ALLOW" if result.is_clean else "BLOCK"
    types = [i.get("type") for i in result.issues[:5]]
    print(f"  {status} risk={result.risk_score:.2f} issues={types}")


def main() -> None:
    print("Benign streamed reply:")
    benign = simulate_stream(["The capital of France is ", "Paris."])
    scan_completed_message(benign)

    print("\nLeaked secret (split across chunks — must scan full buffer):")
    leaked = simulate_stream(
        ["Here is the key: AKIA", "IOSFODNN7", "EXAMPLE"]
    )
    scan_completed_message(leaked)


if __name__ == "__main__":
    main()
