"""AI Infrastructure Service CLI - base typer app."""

import importlib
from pathlib import Path
from typing import Annotated

import typer
from slices_clientlib_aiis import SlicesClientWithAIInfraService

from . import err_console
from .ai_context import AIContextObj
from .context import Context
from .util.typer import AliasGroup

ai_app = typer.Typer(short_help="Basic Infrastructure", no_args_is_help=True, cls=AliasGroup)
AliasGroup.register_hidden_alias("clusters", "cluster")
AliasGroup.register_hidden_alias("list", "jobs")
AliasGroup.register_hidden_alias("show", "job")


def ai_site_callback(ctx: Context, _param: typer.CallbackParam, value: str):
    """Validate bi_infra value."""
    if ctx.resilient_parsing:
        # we are in shell completion, so return anything
        return list(ctx.obj.api.ai_config.ai_service_sites.keys())[0]

    if value not in ctx.obj.api.ai_config.ai_service_sites:
        raise typer.BadParameter(f"Invalid AI Infrastructure Service site ID {value!r}")

    return value


def complete_site_id(incomplete_value: str):
    """Shell completion for infra ID parameter."""
    # Note: this ignores custom config (but we don't have ctx.obj here)
    slices_client = SlicesClientWithAIInfraService(central_config=None, ai_config=None)
    infras_ids = [k for k, v in slices_client.ai_api_clients_config.ai_service_sites.items() if "dev" not in v.tags]
    for infras_id in infras_ids:
        if infras_id.startswith(incomplete_value):
            yield infras_id


DEFAULT_AI_SITE_ID = "be-gent1"


@ai_app.callback(invoke_without_command=False)
def initialize_ai(
    ctx: Context,
    site: Annotated[
        str,
        typer.Option(
            "--site",
            "--site-id",
            envvar=["SLICES_AI_SITE", "SLICES_AI_SITE_ID"],
            callback=ai_site_callback,
            help="AI Infrastructure Service site ID.",
            autocompletion=complete_site_id,
        ),
    ] = DEFAULT_AI_SITE_ID,
):
    """AI Infrastructure Service Commands."""

    if ctx.obj.user_info is None:
        err_console.print("[red]You must be logged in. :x:")
        raise typer.Exit(code=1)

    ctx.obj = AIContextObj(
        api=ctx.obj.api,
        user_info=ctx.obj.user_info,
        site_id=site,
        verbosity=ctx.obj.verbosity,
        project_id=ctx.obj.project_id,
    )


# TODO: add
# print_bugreport_context


def _import_subcommands():
    """Import all ai_subcommands_* files, so we register all the subcommands with typer."""
    current_dir = Path(__file__).parent
    module_files = Path(current_dir).glob("ai_subcommands_*.py")

    for file_path in module_files:
        module_name = file_path.name.replace(".py", "")
        importlib.import_module(f"slices_cli_ai.{module_name}")


_import_subcommands()
