import io
from typing import Dict, List, TextIO


class TeeStream(io.StringIO):
    """Mirrors what a snippet prints, still writing it downstream.

    Snippet output has to reach two places. The Smart Chat needs it as the tool
    result, and the pod's stdout keeps it in kubectl/Elasticsearch. Replacing
    sys.stdout with a plain buffer would satisfy the first and silently drop the
    second, so writes are copied instead of diverted.
    """

    def __init__(self, downstream: TextIO) -> None:
        super().__init__()
        self._downstream = downstream

    def write(self, text: str) -> int:
        super().write(text)
        try:
            return self._downstream.write(text)
        except Exception:
            return len(text)

    def flush(self) -> None:
        try:
            self._downstream.flush()
        except Exception:
            pass


def as_logs(out: str, err: str) -> List[Dict[str, str]]:
    logs = []
    if out:
        logs.append({"type": "stdout", "text": out})
    if err:
        logs.append({"type": "stderr", "text": err})
    return logs
