"""Shared CLI helpers for small operational scripts."""

from __future__ import annotations

import argparse
import subprocess
import textwrap
from collections.abc import Sequence


def _clean_block(text: str) -> str:
    return textwrap.dedent(text).strip()


def build_parser(
    *,
    description: str,
    examples: Sequence[str] = (),
    notes: Sequence[str] = (),
) -> argparse.ArgumentParser:
    epilog_parts: list[str] = []
    if examples:
        rendered_examples = "\n".join(textwrap.indent(_clean_block(example), "  ") for example in examples)
        epilog_parts.append(f"Examples:\n{rendered_examples}")
    epilog_parts.extend(_clean_block(note) for note in notes if _clean_block(note))

    kwargs: dict[str, object] = {"description": description}
    if epilog_parts:
        kwargs["formatter_class"] = argparse.RawDescriptionHelpFormatter
        kwargs["epilog"] = "\n\n".join(epilog_parts)
    return argparse.ArgumentParser(**kwargs)


def format_called_process_error(prefix: str, exc: subprocess.CalledProcessError) -> str:
    for attr in ("stderr", "stdout"):
        value = getattr(exc, attr, None)
        if isinstance(value, str) and value.strip():
            return f"{prefix}: {value.strip()}"
    return f"{prefix}: {exc}"
