"""CLI commands for building artifacts (images, packages)."""
from __future__ import annotations

import click

from k4s.cli.errors import exit_with_error
from k4s.cli.state import CliState
from k4s.cli.target import resolve_target
from k4s.cli.verbosity import apply_command_ui_overrides
from k4s.core.executor import Executor
from k4s.core.products import run_steps
from k4s.recipes.dataiku.base_image import BaseImagePlan, build_base_image_steps


@click.group()
def build():
    """Build artifacts (container images, packages)."""
    pass


@build.command("dataiku-base-image")
@click.option("--context", "context_name", default=None, help="Context name (or 'local'). Uses current context if omitted.")
@click.option("--data-dir", default="/data/dataiku/DATA_DIR", show_default=True, help="Dataiku DSS data directory.")
@click.option("--os-user", default="dataiku", show_default=True, help="OS user that owns the DSS installation.")
@click.option("--tag", default="dss-base-image", show_default=True, help="Docker image tag for the base image.")
@click.option("--distrib", default="almalinux8", show_default=True, help="Base distribution (almalinux8, almalinux9).")
@click.option("--with-cuda", is_flag=True, help="Include CUDA support in the base image.")
@click.option("--cuda-version", default=None, help="CUDA version (e.g. 11.8). Requires --with-cuda.")
@click.option("--with-py311", is_flag=True, help="Include Python 3.11 in the base image.")
@click.option("--without-r", is_flag=True, help="Exclude R from the base image.")
@click.option("--system-packages", default=None, help="Additional system packages to install (comma-separated).")
@click.option("--http-proxy", default=None, help="HTTP proxy for the image build.")
@click.option("--no-proxy", "no_proxy", default=None, help="no_proxy value for the image build.")
@click.option("--push", is_flag=True, help="Push the built image to a registry after building.")
@click.option("--registry", default=None, help="Docker registry URL (required for --push).")
@click.option("--registry-username", default=None, help="Registry username for docker login.")
@click.option("--registry-password", default=None, help="Registry password for docker login (prefer --ask-registry-password).")
@click.option("--ask-registry-password", is_flag=True, help="Prompt for registry password.")
@click.option("--dry-run", is_flag=True, help="Print the plan without applying changes.")
@click.option("-q", "--quiet", is_flag=True, help="Only print final results and errors.")
@click.option("-v", "--verbose", count=True, help="Increase verbosity (-v logs, -vv debug).")
@click.pass_context
def dataiku_base_image(
    ctx,
    context_name,
    data_dir,
    os_user,
    tag,
    distrib,
    with_cuda,
    cuda_version,
    with_py311,
    without_r,
    system_packages,
    http_proxy,
    no_proxy,
    push,
    registry,
    registry_username,
    registry_password,
    ask_registry_password,
    dry_run,
    quiet,
    verbose,
):
    """Build a Dataiku DSS container execution base image.

    Runs dssadmin build-base-image on the target VM where DSS is installed.
    Optionally pushes the image to a Docker registry with --push --registry.

    \b
    Examples:
      k4s build dataiku-base-image
      k4s build dataiku-base-image --tag myimage:v1 --distrib almalinux9
      k4s build dataiku-base-image --with-cuda --cuda-version 11.8
      k4s build dataiku-base-image --push --registry nexus.example.com:8080
    """
    state: CliState = ctx.obj["state"]
    apply_command_ui_overrides(ctx, state, quiet=quiet, verbose=verbose)
    ui = state.ui

    try:
        if cuda_version and not with_cuda:
            raise ValueError("--cuda-version requires --with-cuda.")

        if push and not registry:
            raise ValueError("--push requires --registry.")

        if registry_password and ask_registry_password:
            raise ValueError("Use either --registry-password or --ask-registry-password, not both.")

        if ask_registry_password:
            registry_password = click.prompt(
                "Registry password",
                hide_input=True,
                confirmation_prompt=False,
            )

        c = resolve_target(state, context_name)

        plan = BaseImagePlan(
            data_dir=data_dir.rstrip("/"),
            os_user=os_user,
            tag=tag,
            distrib=distrib,
            with_cuda=with_cuda,
            cuda_version=cuda_version,
            with_py311=with_py311,
            without_r=without_r,
            system_packages=system_packages,
            http_proxy=http_proxy,
            no_proxy=no_proxy,
            push=push,
            registry=registry,
            registry_username=registry_username,
            registry_password=registry_password,
        )

        ex = Executor(c.to_server_config())
        if dry_run:
            steps = build_base_image_steps(ui, ex, plan)
            run_steps(ui, steps, dry_run=True)
        else:
            with ex:
                steps = build_base_image_steps(ui, ex, plan)
                run_steps(ui, steps, dry_run=False)
            state.history.append(
                action="build",
                product="dataiku-base-image",
                context=c.name,
                host=c.host,
                params={
                    "tag": tag,
                    "distrib": distrib,
                    "with_cuda": with_cuda,
                    "push": push,
                    "registry": registry,
                },
            )
            ui.success(f"Base image built successfully: {tag}")
    except Exception as e:
        exit_with_error(ctx, ui, e, code=1)
