"""Tests for CLI ergonomic fixes shipped in v0.17.1.

Covers:

  - PAPER-18 — `mgf-common doctor` reads ``__version__`` from the
    imported package, not from ``importlib.metadata`` (which goes
    stale during editable-install dev workflows).
  - PAPER-19 — the ``mgf-common`` console-script entry point self-
    bootstraps via ``bootstrap_for_test`` so subcommands that
    read identity (``explain``, future settings-aware surfaces)
    don't emit ``UnconfiguredWarning`` on stderr.
"""

from __future__ import annotations

import io
import warnings
from contextlib import redirect_stderr, redirect_stdout

from mgf.common._identity import UnconfiguredWarning

# ---------------------------------------------------------------------------
# PAPER-18 — doctor uses __version__, not importlib.metadata.version
# ---------------------------------------------------------------------------


class TestDoctorVersionReflection:
    """Pin: doctor's first-line banner reflects ``mgf.common.__version__``,
    not a stale ``importlib.metadata.version()`` value (which can lag
    behind the source tree by a series of bumps in editable installs)."""

    def test_install_check_reports_current_version(self) -> None:
        from mgf.common import __version__

        from mgf.fed.cli._doctor import _check_install

        # _check_install yields tuples; the install row is the first.
        marker, msg, _action = next(iter(_check_install()))
        assert marker == "✓", f"install check unexpectedly non-OK: {msg}"
        assert f"v{__version__}" in msg, (
            f"doctor must report the imported package's __version__ "
            f"(currently {__version__}), not a stale metadata value. "
            f"Got: {msg}"
        )

    def test_install_check_does_not_use_metadata_version(self) -> None:
        # Belt-and-suspenders: the source line MUST source from
        # `mgf.common.__version__`, not `importlib.metadata.version`.
        # Read the function source and verify the import shape.
        import inspect

        from mgf.fed.cli import _doctor

        source = inspect.getsource(_doctor._check_install)
        assert "from mgf.common import __version__" in source, (
            "PAPER-18 fix regressed — _check_install must import "
            "__version__ directly from mgf.common"
        )


# ---------------------------------------------------------------------------
# PAPER-19 — CLI self-bootstraps so subcommands don't emit
# UnconfiguredWarning on stderr.
# ---------------------------------------------------------------------------


class TestCliSelfBootstrap:
    """Pin: running `mgf-common <subcommand>` through `main()` MUST
    NOT emit ``UnconfiguredWarning`` on stderr, because the CLI is
    a host process that bootstraps itself before dispatching."""

    def test_explain_via_main_emits_no_unconfigured_warning(self) -> None:
        # Run `mgf-common explain` end-to-end, capturing stderr +
        # warnings. The pre-fix behaviour fires UnconfiguredWarning
        # because explain reads identity. The fix self-bootstraps
        # the dispatcher before subcommand handlers run.
        # PAPER-19's self-bootstrap identity ("mgf-common-cli") is a
        # property of the mgf-common console-script entry point, which now
        # lives (vestigially) in mgf.fed.cli._mgfcli.main — not fed's
        # fleet-orchestrator __main__.main.
        from mgf.fed.cli._mgfcli import main

        out_buf = io.StringIO()
        err_buf = io.StringIO()
        with warnings.catch_warnings(record=True) as caught:
            warnings.simplefilter("always")
            with redirect_stdout(out_buf), redirect_stderr(err_buf):
                exit_code = main(["explain"])

        assert exit_code == 0
        unconfigured = [w for w in caught if issubclass(w.category, UnconfiguredWarning)]
        assert unconfigured == [], (
            f"explain via main() emitted UnconfiguredWarning — the CLI "
            f"is supposed to self-bootstrap. Got: "
            f"{[str(w.message) for w in unconfigured]}"
        )

        # Side-benefit pin from the PAPER-19 retrospective: explain's
        # banner shows real identity, not the `vunknown` placeholder.
        out = out_buf.getvalue()
        assert "vunknown" not in out, (
            f"explain banner showed `vunknown` placeholder — the CLI "
            f"self-bootstrap should set identity to `mgf-common-cli`. "
            f"Got banner output: {out[:200]}"
        )

    def test_main_bootstraps_with_mgf_common_cli_identity(self) -> None:
        # Pin the identity the CLI sets so consumers grepping for it
        # in their own logs / stack traces have a stable name.
        # PAPER-19's self-bootstrap identity ("mgf-common-cli") is a
        # property of the mgf-common console-script entry point, which now
        # lives (vestigially) in mgf.fed.cli._mgfcli.main — not fed's
        # fleet-orchestrator __main__.main.
        from mgf.fed.cli._mgfcli import main

        out_buf = io.StringIO()
        with redirect_stdout(out_buf):
            main(["explain"])

        out = out_buf.getvalue()
        assert "mgf-common-cli" in out, (
            f"CLI self-bootstrap should set app_name to 'mgf-common-cli'. Banner: {out[:200]}"
        )
