"""``mgf-fed federation`` + ``mgf-fed design`` — surface the federation
contract and the foundation design papers from the installed
``mgf-standard`` corpus.

Companions to ``mgf-fed standards``: where ``standards`` prints the *rules*,
``federation`` prints the *contract* (``FEDERATION.md`` — duties, layering,
conformance levels) and ``design`` prints the foundation *design* papers (the
WHY behind the rules). All resolve from the ``mgf-standard`` version this
project pins, via that package's public seams (:func:`mgf.standard.federation`,
:func:`mgf.standard.list_design`, :func:`mgf.standard.read_design`).

Like ``standards``/``sync-prompt`` they degrade LOUDLY — a non-zero exit and the
exact install command — when the optional ``[standards]`` corpus extra is absent,
so an agent never gets a silent partial answer.
"""

from __future__ import annotations

import sys
from typing import TYPE_CHECKING

from mgf.common.cli import EXIT_OPERATION_ERROR, EXIT_SUCCESS

if TYPE_CHECKING:
    import argparse

_INSTALL_HINT = "    pip install -U 'mgf-common[standards]'   (or: uv add 'mgf-common[standards]')"


def _corpus_missing(what: str) -> int:
    """Print the loud, actionable corpus-missing error and return non-zero."""
    print(
        f"error: the {what} is not installed. It ships in the `mgf-standard` "
        f"extra — install it:\n{_INSTALL_HINT}\n"
        "The corpus is an optional, Codeberg-only extra; a plain mgf-common "
        "install does not carry it.",
        file=sys.stderr,
    )
    return EXIT_OPERATION_ERROR


def run_federation(args: argparse.Namespace) -> int:
    """Print the federation contract (``FEDERATION.md``), resolved from the corpus."""
    try:
        from mgf.standard import federation
    except (ModuleNotFoundError, ImportError):
        return _corpus_missing("federation contract")
    try:
        text = federation()
    except FileNotFoundError:
        return _corpus_missing("federation contract")
    print(text, end="" if text.endswith("\n") else "\n")
    return EXIT_SUCCESS


def add_design_args(parser: argparse.ArgumentParser) -> None:
    """Register the ``design`` subcommand's arguments."""
    parser.add_argument(
        "paper",
        nargs="?",
        default=None,
        help="Design paper to print (e.g. federation). Omit to list all available papers.",
    )


def run_design(args: argparse.Namespace) -> int:
    """List the foundation design papers, or print one by name."""
    try:
        from mgf.standard import list_design, read_design
    except (ModuleNotFoundError, ImportError):
        return _corpus_missing("design corpus")
    try:
        papers = list_design()
    except FileNotFoundError:
        return _corpus_missing("design corpus")

    if args.paper is None:
        print("Foundation design papers (print one with `mgf-fed design <name>`):")
        for name in papers:
            print(f"  {name}")
        return EXIT_SUCCESS

    try:
        text = read_design(args.paper)
    except FileNotFoundError:
        print(
            f"error: unknown design paper {args.paper!r}. Available: {', '.join(papers)}.",
            file=sys.stderr,
        )
        return EXIT_OPERATION_ERROR
    print(text, end="" if text.endswith("\n") else "\n")
    return EXIT_SUCCESS
