"""Session-wide pytest hooks for the mgf-common suite."""

from __future__ import annotations

import os
import sys

import pytest

# The true platform identity, captured at import — before any test
# monkeypatches ``os.name`` / ``sys.platform`` to simulate another OS.
_REAL_OS_NAME = os.name
_REAL_SYS_PLATFORM = sys.platform


@pytest.hookimpl(wrapper=True)
def pytest_runtest_makereport():  # type: ignore[no-untyped-def]
    """Keep failure reporting robust against OS-simulation tests.

    Several tests monkeypatch ``os.name='nt'`` / ``sys.platform`` to drive the
    Windows / macOS path branches. ``monkeypatch`` only restores during
    teardown — AFTER this report hook — so if such a test *fails* while patched,
    pytest's own representation code (e.g. ``Path(os.getcwd())``) raises
    ``NotImplementedError: cannot instantiate 'WindowsPath'`` and aborts the
    WHOLE session with an INTERNALERROR, masking the real failure (it took the
    matrix actually running on 3.11 to surface this).

    Restore the true platform identity for the duration of report generation,
    then put the patched values back so the failing test's own teardown stays
    consistent.
    """
    patched = (os.name, sys.platform)
    os.name, sys.platform = _REAL_OS_NAME, _REAL_SYS_PLATFORM
    try:
        return (yield)
    finally:
        os.name, sys.platform = patched
