"""命令行进程与子进程默认使用 UTF-8（Windows / Linux 一致）。"""

from __future__ import annotations

import os
import sys


def configure_cli_utf8() -> None:
    """
    - 为当前进程设置 ``PYTHONIOENCODING`` / ``PYTHONUTF8``（供本进程及子进程继承）。
    - 将 ``stdin`` / ``stdout`` / ``stderr`` 重配置为 UTF-8（在支持的 Python 版本上）。
    """
    os.environ.setdefault("PYTHONIOENCODING", "utf-8")
    os.environ.setdefault("PYTHONUTF8", "1")
    for stream in (sys.stdout, sys.stderr, sys.stdin):
        if stream is None:
            continue
        reconf = getattr(stream, "reconfigure", None)
        if callable(reconf):
            try:
                reconf(encoding="utf-8", errors="replace")
            except (OSError, ValueError, TypeError, AttributeError):
                pass


def subprocess_env_utf8(base: dict[str, str] | None = None) -> dict[str, str]:
    """合并环境变量，保证子进程显式带上 UTF-8 相关项（不覆盖调用方已设值）。"""
    out = dict(os.environ if base is None else {**os.environ, **base})
    out.setdefault("PYTHONIOENCODING", "utf-8")
    out.setdefault("PYTHONUTF8", "1")
    return out
