"""Functions for executing subcommand CLIs."""

import os
import shutil
import sys

from . import console, console_trace, err_console
from .find_subcommands import find_subcommand
from .help import print_help


def exec_subcommand(command: str):
    """Execute a subcommand CLI."""

    subcommand = find_subcommand(command)
    if not subcommand:
        err_console.print(f"[red bold] :x: Unrecognized command {command}", highlight=False)
        print_help()
        sys.exit(1)

    # Remove --no-upgrade-check
    argv = [a for a in sys.argv if a != "--no-upgrade-check"]

    console_trace.print(f"Executing {subcommand.executable} with args {argv[1:]}")

    try:
        os.execvp(subcommand.executable, argv)  # noqa: S606
    except:  # noqa: E722
        console.print(f"[red] :x: Could not find {subcommand.executable}. Did you install it correctly?")
        console.print(f"[grey]Debug info: which={shutil.which(subcommand.executable)} PATH={os.environ['PATH']}")
        sys.exit(1)
