"""Make ``os.environ`` able to hold UTF-8 values (e.g. Polish letters in .env) when the interpreter's filesystem encoding is ASCII.

Cause of the 2026-11-13 outage: lswsgi starts Python without LANG, so ``sys.getfilesystemencoding()`` is ASCII and
``os.environ[key] = "...ś..."`` - which ``dotenv.load_dotenv`` performs for every value - raises ``UnicodeEncodeError``
while importing flask_app.py (HTTP 500 on every page).

``use_utf8_environment`` replaces only the VALUE codecs of the existing ``os.environ`` object with UTF-8 (+ surrogateescape, the
same error handler the default codec uses). Values are then stored as the exact UTF-8 bytes, ``os.environ.get``/``os.getenv``
return the original text, ``os.environb`` and child processes see the same bytes. Nothing is skipped, replaced or defaulted,
and ``load_dotenv`` itself stays unchanged. In a UTF-8 environment (or on Windows) the call changes nothing.
Importing this module performs no I/O.
"""
import os

_SAMPLE = 'ś'


def use_utf8_environment(environ=None):
    """Returns True when the codecs were replaced, False when nothing needed (or could safely be) changed."""
    environ = os.environ if environ is None else environ
    if os.name != 'posix' or not all(hasattr(environ, name) for name in ('encodevalue', 'decodevalue')):
        return False
    try:
        if environ.encodevalue(_SAMPLE) == _SAMPLE.encode('utf-8'):
            return False                                          # already UTF-8 (normal LANG): leave everything alone
    except UnicodeError:
        pass
    previous = environ.encodevalue, environ.decodevalue
    environ.encodevalue = lambda value: value.encode('utf-8', 'surrogateescape')
    environ.decodevalue = lambda value: value.decode('utf-8', 'surrogateescape')
    if environ.encodevalue(_SAMPLE) != _SAMPLE.encode('utf-8') or environ.decodevalue(_SAMPLE.encode('utf-8')) != _SAMPLE:
        environ.encodevalue, environ.decodevalue = previous       # never leave a half-patched environment
        return False
    return True
