"""CLI entry point for ``example_app``.

Demonstrates v0.4 Phase E (composable CLI) by registering a
custom subcommand against the ``mgf.common.cli`` registry, then
building a top-level CLI via :func:`mgf.common.cli.build_cli`
without touching :mod:`argparse` directly.
"""

from __future__ import annotations

import argparse
import sys
from typing import TYPE_CHECKING

from mgf.common import bootstrap
from mgf.common.cli import (
    EXIT_SUCCESS,
    build_cli,
    register_cli_subcommand,
)
from mgf.common.cli._subcommand_registry import dispatch
from mgf.common.observability import get_logger

from example_app.settings import AppSettings

if TYPE_CHECKING:
    from collections.abc import Sequence

LOG = get_logger(__name__)


def _setup_greet(parser: argparse.ArgumentParser) -> None:
    """Wire ``--name`` for the ``greet`` subcommand."""
    parser.add_argument(
        "--name",
        default="world",
        help="Whom to greet. Defaults to 'world'.",
    )


@register_cli_subcommand(
    "greet",
    help="Print a friendly greeting using the configured greeting prefix.",
    parser_setup=_setup_greet,
)
def run_greet(args: argparse.Namespace) -> int:
    """Handler for the ``greet`` subcommand."""
    settings = AppSettings()
    LOG.info("greeting %s", args.name)
    print(f"{settings.greeting}, {args.name}!")
    return EXIT_SUCCESS


def main(argv: Sequence[str] | None = None) -> int:
    """Console-script entry point for ``example-app``.

    Wires identity + observability via ``bootstrap()`` (auto-derives
    from package metadata since this is run via the console-script
    entry that preserves ``__spec__``), then dispatches through the
    shared ``mgf.common.cli`` registry.
    """
    if argv is None:
        argv = sys.argv[1:]

    settings = AppSettings()

    # Build a fresh CLI parser using the consumer-side prog name.
    # Since the CLI extraction, the shared diagnostic subcommands
    # (app-doctor / explain / validate / ...) are REGISTERED by
    # mgf-fed[cli] at import time; ``include_builtins=True`` makes
    # whatever is registered visible from this binary. Import the
    # provider softly so the app still works without it.
    try:  # pragma: no cover - exercised via the CLI tests
        import mgf.fed.cli  # noqa: F401  (registration side-effect)
    except ImportError:
        pass
    parser = build_cli(
        prog="example-app",
        description="Reference second-consumer of mgf-common.",
        include_builtins=True,
    )

    args = parser.parse_args(list(argv))

    # Bootstrap mgf-common with our composed settings. Identity is
    # explicit because tests / scripts may invoke main() in
    # contexts where __spec__ derivation doesn't fire.
    with bootstrap(
        app_name="example-app",
        app_version="0.0.1",
        settings=settings.mgf,
    ):
        return dispatch(args, parser=parser)


if __name__ == "__main__":
    raise SystemExit(main())
