"""Tests for ``mgf-common new-project-prompt`` + ``adopt-prompt`` (Cases B & C).

Each prints a federation entry-point prompt resolved through
``mgf.standard.read_recipe`` (the new-project / adopt recipes, shipped in
``mgf-standard`` >= 0.1.52), the bootstrap + adopt companions to ``sync-prompt``.
They degrade with an actionable error if that seam is unavailable.
"""

from __future__ import annotations

import argparse
import io
from contextlib import redirect_stderr, redirect_stdout

from mgf.common.cli._exit_codes import EXIT_SUCCESS, EXIT_UNKNOWN

from mgf.fed.cli import _recipe_prompt
from mgf.fed.cli._recipe_prompt import (
    run_adopt_prompt,
    run_new_project_prompt,
    run_onboard_prompt,
)


def _args() -> argparse.Namespace:
    return argparse.Namespace()


class TestNewProjectPrompt:
    def test_prints_recipe_and_returns_exit_ok(self) -> None:
        buf = io.StringIO()
        with redirect_stdout(buf):
            rc = run_new_project_prompt(_args())
        assert rc == EXIT_SUCCESS
        # stable marker from the Case-B prompt body
        assert "bootstrapping an EMPTY repository" in buf.getvalue()

    def test_output_ends_with_a_newline(self) -> None:
        buf = io.StringIO()
        with redirect_stdout(buf):
            run_new_project_prompt(_args())
        assert buf.getvalue().endswith("\n")


class TestAdoptPrompt:
    def test_prints_recipe_and_returns_exit_ok(self) -> None:
        buf = io.StringIO()
        with redirect_stdout(buf):
            rc = run_adopt_prompt(_args())
        assert rc == EXIT_SUCCESS
        # stable marker from the Case-C prompt body
        assert "NOT a Magogi Foundation" in buf.getvalue()


class TestOnboardPrompt:
    def test_prints_recipe_and_returns_exit_ok(self) -> None:
        buf = io.StringIO()
        with redirect_stdout(buf):
            rc = run_onboard_prompt(_args())
        assert rc == EXIT_SUCCESS
        # stable marker from the onboard prompt body
        assert "bringing an EXISTING, non-MGF project INTO" in buf.getvalue()


class TestUnresolvable:
    def test_errors_with_guidance_and_fails_closed(self, monkeypatch) -> None:
        # Simulate a missing mgf-standard corpus: resolver returns None → the
        # command must fail closed (non-zero, NO partial prompt) with a LOUD,
        # actionable install message.
        monkeypatch.setattr(_recipe_prompt, "_resolve_recipe", lambda _recipe: None)
        out, err = io.StringIO(), io.StringIO()
        with redirect_stdout(out), redirect_stderr(err):
            rc = run_adopt_prompt(_args())
        assert rc == EXIT_UNKNOWN
        assert "pip install -U 'mgf-common[standards]'" in err.getvalue()
        assert out.getvalue() == ""  # no partial prompt on a degraded resolve
