#!/usr/bin/env python3
"""Sanitize text for the Even Realities G2 glasses TextContainer.

The glasses firmware silently DROPS any character outside its single embedded
LVGL font. So before quoting captured agent output back to the display we:
  - replace common smart-punctuation with ASCII equivalents,
  - strip ANSI escape sequences (tmux capture can carry them),
  - drop any remaining non-printable / non-ASCII byte,
  - collapse runs of blank lines (the screen is ~400-500 chars/page).

Reusable by the future /api/voice/answer route or by me when hand-quoting a
pane. Keep it tiny and dependency-free.
"""
import re

_ANSI = re.compile(r"\x1b\[[0-9;?]*[a-zA-Z]|\x1b\][^\x07]*\x07")
_SMART = {
    "‘": "'", "’": "'", "“": '"', "”": '"',
    "–": "-", "—": "-", "…": "...", " ": " ",
    "•": "*", "×": "x", "→": "->", "←": "<-",
    "✓": "ok", "✗": "x", "●": "*", "○": "-",
}
_NONASCII = re.compile(r"[^\x20-\x7E\n]")
_BLANKS = re.compile(r"\n{3,}")


def sanitize(text: str, max_chars: int = 300) -> str:
    """Return glasses-safe ASCII, trimmed to max_chars (None = no trim)."""
    text = _ANSI.sub("", text)
    for bad, good in _SMART.items():
        text = text.replace(bad, good)
    text = _NONASCII.sub("", text)
    text = _BLANKS.sub("\n\n", text)
    # normalize trailing whitespace per line
    text = "\n".join(line.rstrip() for line in text.split("\n")).strip()
    if max_chars and len(text) > max_chars:
        text = text[: max_chars - 3].rstrip() + "..."
    return text


if __name__ == "__main__":
    import sys
    data = sys.stdin.read() if not sys.argv[1:] else " ".join(sys.argv[1:])
    print(sanitize(data))
