"""Console output helpers that degrade safely on non-UTF-8 terminals."""

from __future__ import annotations

import sys
from typing import TextIO


def safe_console_text(text: str, *, encoding: str | None = None) -> str:
    """Return text that won't crash when written to the target encoding."""
    target_encoding = encoding or getattr(sys.stdout, "encoding", None) or "utf-8"
    try:
        text.encode(target_encoding)
        return text
    except UnicodeEncodeError:
        safe_chars = []
        for char in text:
            try:
                char.encode(target_encoding)
            except UnicodeEncodeError:
                continue
            safe_chars.append(char)
        safe_text = "".join(safe_chars)
        # If a decorative prefix was stripped, drop the orphaned leading space too.
        if safe_text and safe_text[0].isspace() and text and not text[0].isspace():
            safe_text = safe_text.lstrip()
        return safe_text


def console_print(message: str = "", *, file: TextIO | None = None) -> None:
    """Print user-facing text without raising on limited terminal encodings."""
    stream = file or sys.stdout
    print(safe_console_text(message, encoding=getattr(stream, "encoding", None)), file=stream)
