from __future__ import annotations

import traceback

import click

from k4s.core.executor import ExecutorError
from k4s.ui.ui import Ui, Verbosity

# Exception types whose messages are self-explanatory.
# Tracebacks for these add noise without diagnostic value.
_KNOWN_ERROR_TYPES = (ExecutorError, KeyError, ValueError, click.ClickException)


def exit_with_error(ctx: click.Context, ui: Ui, exc: BaseException, *, code: int = 1) -> None:
    """Print a user-friendly error and exit.

    - All verbosities: concise error message.
    - debug (-vv): adds Python traceback **only** for unexpected
      exceptions (not ExecutorError, KeyError, etc.) whose message
      alone may not be sufficient for diagnosis.
    """
    if isinstance(exc, KeyError) and exc.args:
        msg = exc.args[0]
    else:
        msg = str(exc)
    ui.error(msg)
    if ui.options.verbosity >= Verbosity.debug and not isinstance(exc, _KNOWN_ERROR_TYPES):
        ui.debug(traceback.format_exc())
    ctx.exit(code)

