"""User-perspective tests for ``mgf.common`` lifecycle.

Surfaces exercised:
  - :func:`mgf.common.bootstrap`
  - :func:`mgf.common.bootstrap_for_test`
  - :class:`mgf.common.AppContext` (both bootstrap-owned and scoped)
  - :func:`mgf.common.current_context`
  - :func:`mgf.common.app_name` / :func:`mgf.common.app_version`
"""

from __future__ import annotations

import mgf.common


class TestBootstrap:
    def test_returns_appcontext(self, app_ctx: mgf.common.AppContext) -> None:
        """``bootstrap()`` (via ``bootstrap_for_test``) returns an
        ``AppContext`` directly. Type-checks against the public
        class, not a private wrapper."""
        assert isinstance(app_ctx, mgf.common.AppContext)
        assert app_ctx.app_name == "test-app"
        assert app_ctx.app_version == "0.0.1"

    def test_current_context_returns_active(
        self,
        app_ctx: mgf.common.AppContext,
    ) -> None:
        assert mgf.common.current_context() is app_ctx

    def test_app_name_routes_through_context(
        self,
        app_ctx: mgf.common.AppContext,
    ) -> None:
        assert mgf.common.app_name() == "test-app"
        assert mgf.common.app_version() == "0.0.1"

    def test_with_block_yields_same_object(self) -> None:
        """``with bootstrap_for_test() as ctx:`` yields the same
        AppContext that ``current_context()`` returns."""
        with mgf.common.bootstrap_for_test() as ctx:
            assert mgf.common.current_context() is ctx


class TestScopedAppContext:
    """Multi-tenancy via direct ``AppContext`` construction
    (FEEDBACK API-02; v0.4.2)."""

    def test_scoped_overlays_global(
        self,
        app_ctx: mgf.common.AppContext,
    ) -> None:
        with mgf.common.AppContext("plugin", "9.9.9"):
            assert mgf.common.app_name() == "plugin"
            assert mgf.common.app_version() == "9.9.9"
        # After: routes back to the bootstrap-owned context
        assert mgf.common.app_name() == "test-app"

    def test_nested_scopes_innermost_wins(
        self,
        app_ctx: mgf.common.AppContext,
    ) -> None:
        with mgf.common.AppContext("middle", "1.0"):
            with mgf.common.AppContext("inner", "2.0"):
                assert mgf.common.app_name() == "inner"
            assert mgf.common.app_name() == "middle"

    def test_scoped_default_settings_is_fresh_instance(self) -> None:
        from mgf.common.settings import MgfSettings

        ctx = mgf.common.AppContext("plugin", "1.0")
        assert isinstance(ctx.settings, MgfSettings)
