# Copyright 2026 SigmaSRC, Inc. All Rights Reserved.

"""Force the interpreter into Python UTF-8 Mode (PEP 540).

UTF-8 Mode makes ``open()`` / ``os.popen()`` / ``subprocess`` text I/O default to
UTF-8 regardless of the host locale.  This is required for correct handling of
non-ASCII host data (accented French/German usernames, GECOS names, filenames,
package descriptions) and Fuel source on hosts whose locale is ``C``/``POSIX`` or
a legacy 8-bit codepage -- where the default encoding would otherwise be ASCII or
Latin-1 and silently mojibake or raise ``UnicodeDecodeError``.

UTF-8 Mode can only be enabled at interpreter startup, so if we are not already
running in it we set ``PYTHONUTF8`` in the environment and re-exec this same
interpreter.  ``os.execv`` preserves the PID, so this is transparent to systemd
and the Windows SCM.  Child processes the agent spawns (engine, gather, ...)
inherit ``PYTHONUTF8`` through the environment and therefore also start in UTF-8
Mode.

Call ``ensure_utf8_mode()`` as the very first thing in a top-level entry point,
before any other side effects (logging setup, argument parsing, file opens).
"""

import os
import sys


def ensure_utf8_mode():
    """Re-exec the current interpreter in UTF-8 Mode if it is not already on."""
    if sys.flags.utf8_mode:
        # Already in UTF-8 Mode (env/-X set by the service unit or a parent).
        return
    os.environ["PYTHONUTF8"] = "1"
    os.environ.setdefault("PYTHONIOENCODING", "utf-8")
    try:
        os.execv(sys.executable, [sys.executable] + sys.argv)
    except OSError:
        # Re-exec failed (unusual embedding/permissions).  The explicit
        # encoding="utf-8" pins at the protocol-critical boundaries still apply,
        # so degrade gracefully rather than abort the agent.
        pass
