"""Tests for ``mgf-common federation`` + ``mgf-common design`` (WU5).

These surface the federation contract (``FEDERATION.md``) and the foundation
design papers from the installed ``mgf-standard`` corpus, and — like the
other federation CLI commands — degrade LOUDLY (non-zero + the exact install
command) when the optional ``[standards]`` corpus extra is absent.
"""

from __future__ import annotations

import argparse
import io
from contextlib import redirect_stderr, redirect_stdout

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

from mgf.fed.cli._federation import run_design, run_federation


def _ns(**kw: object) -> argparse.Namespace:
    return argparse.Namespace(**kw)


class TestFederationCmd:
    def test_prints_the_contract(self) -> None:
        out = io.StringIO()
        with redirect_stdout(out):
            rc = run_federation(_ns())
        assert rc == EXIT_SUCCESS
        assert "FEDERATION" in out.getvalue()
        assert out.getvalue().endswith("\n")

    def test_degrades_loudly_when_corpus_missing(self, monkeypatch) -> None:
        import mgf.standard

        def _raise() -> str:
            raise FileNotFoundError

        monkeypatch.setattr(mgf.standard, "federation", _raise)
        out, err = io.StringIO(), io.StringIO()
        with redirect_stdout(out), redirect_stderr(err):
            rc = run_federation(_ns())
        assert rc == EXIT_OPERATION_ERROR
        assert out.getvalue() == ""  # no partial contract
        assert "mgf-common[standards]" in err.getvalue()


class TestDesignCmd:
    def test_lists_papers(self) -> None:
        out = io.StringIO()
        with redirect_stdout(out):
            rc = run_design(_ns(paper=None))
        assert rc == EXIT_SUCCESS
        assert "federation" in out.getvalue()

    def test_prints_one_paper(self) -> None:
        out = io.StringIO()
        with redirect_stdout(out):
            rc = run_design(_ns(paper="federation"))
        assert rc == EXIT_SUCCESS
        assert out.getvalue().strip()

    def test_unknown_paper_is_nonzero_with_available(self) -> None:
        out, err = io.StringIO(), io.StringIO()
        with redirect_stdout(out), redirect_stderr(err):
            rc = run_design(_ns(paper="no-such-paper"))
        assert rc == EXIT_OPERATION_ERROR
        assert "unknown design paper" in err.getvalue()
        assert "federation" in err.getvalue()  # lists what IS available

    def test_degrades_loudly_when_corpus_missing(self, monkeypatch) -> None:
        import mgf.standard

        def _raise() -> list[str]:
            raise FileNotFoundError

        monkeypatch.setattr(mgf.standard, "list_design", _raise)
        out, err = io.StringIO(), io.StringIO()
        with redirect_stdout(out), redirect_stderr(err):
            rc = run_design(_ns(paper=None))
        assert rc == EXIT_OPERATION_ERROR
        assert "mgf-common[standards]" in err.getvalue()
