#!/usr/bin/python3 -sP

import click

import tmt.cli
import tmt.utils


def show_exception(exception: BaseException) -> None:
    """ Show exception in red, handle exception chain """
    click.echo(click.style(str(exception), fg='red'), err=True)

    # Mention also the original exception if provided
    if exception.__cause__:
        click.echo("The exception was caused by the previous exception:", err=True)
        show_exception(exception.__cause__)


try:
    tmt.cli.main()

# Show detailed output upon command execution errors
except tmt.utils.RunError as error:
    # Check verbosity level used during raising exception,
    # Supported way to correctly get verbosity is
    # tmt.util.Common.opt('verbose')
    if isinstance(error.caller, tmt.utils.Common):
        verbose = error.caller.opt('verbose')
    else:
        verbose = 0
    for name, output in (('stdout', error.stdout), ('stderr', error.stderr)):
        if not output:
            continue
        lines = output.strip().split('\n')
        # Show all lines in verbose mode, limit to maximum otherwise
        if verbose > 0:
            line_summary = f"{len(lines)}"
        else:
            line_summary = f"{min(len(lines), tmt.utils.OUTPUT_LINES)}/{len(lines)}"
            lines = lines[-tmt.utils.OUTPUT_LINES:]
        print(
            f"\n{name} ({line_summary} lines)"
            f"\n{tmt.utils.OUTPUT_WIDTH * '~'}\n" +
            '\n'.join(lines))
    print()
    show_exception(error)
    raise SystemExit(2)

# Basic error message for general errors
except tmt.utils.GeneralError as error:
    show_exception(error)
    raise SystemExit(2)
