"""
Copyright © 2025-2026 Omnissa, LLC.
"""

import subprocess
import sys
from importlib import import_module, reload
from importlib.metadata import distributions

import click

from .util import CtxpException


def ensure_extension(required: str, parent_module_name: str = None):
    installed = {dist.metadata["Name"].lower() for dist in distributions()}
    if required in installed:
        return

    msg = f"This command requires an extension: {required}. Install now?"
    click.confirm(click.style(msg, fg="yellow"), default=True, abort=True)

    cmd = f"pip install {required}"
    try:
        msg = f"Executing: '{cmd}'"
        click.echo(click.style(msg, fg="yellow"))
        subprocess.run(cmd, stdout=sys.stdout, stderr=sys.stderr, text=True, shell=True, check=True)
    except Exception as e:
        error_message = f"Fail installing extensions. Error details: {e}"
        raise CtxpException(error_message)

    if parent_module_name:
        m = import_module(parent_module_name)
        reload(m)
    else:
        import_module(required.replace("-", "_"))
