"""Stage/backstage detection.

Two signals mark the Mercury app view (see staging.py): the app's shadow
session name (``__mercury__`` in ``JPY_SESSION_NAME`` — per-view, primary)
and the ``MERCURY_CONFIG_DIR`` env var (server-level fallback, only set by
``mercury --working-dir``). Either one means "a client may be looking".
"""

import pytest
from genesyscalc import staging


@pytest.fixture(autouse=True)
def clean_stage_env(monkeypatch):
    monkeypatch.delenv("MERCURY_CONFIG_DIR", raising=False)
    monkeypatch.delenv("JPY_SESSION_NAME", raising=False)


def test_backstage_by_default(capsys):
    assert not staging.on_stage()
    staging.backstage("visible")
    assert capsys.readouterr().out == "visible\n"


def test_plain_session_name_is_backstage(monkeypatch, capsys):
    # A JupyterLab or nbconvert session: the real notebook path, no marker.
    monkeypatch.setenv("JPY_SESSION_NAME", "notebooks/genesys_token_calculator.ipynb")
    assert not staging.on_stage()
    staging.backstage("visible")
    assert capsys.readouterr().out == "visible\n"


def test_mercury_shadow_session_is_stage(monkeypatch, capsys):
    # The Mercury app runs against a shadow copy: <stem>__mercury__<id>.ipynb
    monkeypatch.setenv(
        "JPY_SESSION_NAME", "notebooks/genesys_token_calculator__mercury__545e5520.ipynb"
    )
    assert staging.on_stage()
    staging.backstage("hidden")
    assert capsys.readouterr().out == ""


def test_config_dir_fallback_is_stage(monkeypatch, capsys):
    monkeypatch.setenv("MERCURY_CONFIG_DIR", "/tmp/app")
    assert staging.on_stage()
    staging.backstage("hidden")
    assert capsys.readouterr().out == ""


def test_backstage_md_renders_only_off_stage(monkeypatch, capsys):
    # Off stage it must emit SOMETHING (rich markdown under a kernel;
    # IPython's display degrades to print under plain pytest) …
    staging.backstage_md("**visible**")
    assert capsys.readouterr().out != ""

    # … and on stage — either signal — nothing at all.
    monkeypatch.setenv(
        "JPY_SESSION_NAME", "notebooks/genesys_token_calculator__mercury__ab12cd34.ipynb"
    )
    staging.backstage_md("**hidden**")
    assert capsys.readouterr().out == ""
