"""Print version of slices-cli."""

import sys
from importlib.metadata import distributions
from importlib.metadata import version as metadata_version

from . import console, err_console
from .find_subcommands import find_subcommands, warn_if_completion_not_installed
from .get_version import get_executable_version


def print_version():
    """Print the version of slices-cli.

    This also prints the version of the slices subcommands CLIs, and slices clientlibs.
    """

    console.print(f"Slices CLI v{metadata_version('slices-cli')}", highlight=False)
    subcommands = find_subcommands()
    warn_if_completion_not_installed(subcommands)

    core_subcommand = next((subcommand for subcommand in subcommands if subcommand.is_core), None)
    if not core_subcommand:
        err_console.print("[red bold] :x: Slices CLI core is missing.", highlight=False)
        sys.exit(2)

    if core_subcommand.cached_subcommand_version:
        console.print(
            f"   Slices CLI core {core_subcommand.cached_subcommand_version}",
            highlight=False,
        )
    else:
        console.print(
            f"   Slices CLI core {get_executable_version(core_subcommand.executable)}",
            highlight=False,
        )

    for subcommand in subcommands:
        if subcommand.is_core:
            continue

        if subcommand.cached_subcommand_version:
            console.print(
                f"   Slices CLI {subcommand.name} {subcommand.cached_subcommand_version}",
                highlight=False,
            )
        else:
            console.print(
                f"   Slices CLI {subcommand.name} {get_executable_version(subcommand.executable)}",
                highlight=False,
            )

    for dist in distributions():
        if dist.name.startswith("slices-clientlib-"):
            clientlib_name = dist.name[len("slices-clientlib-") :]
            if clientlib_name == "aiis":
                clientlib_name = "ai"
            console.print(f"   Slices clientlib {clientlib_name} v{dist.version}", highlight=False)
