import logging
import os

import click

from k4s.cli.commands.build import build
from k4s.cli.commands.cluster import cluster
from k4s.cli.commands.create import create
from k4s.cli.commands.export import export
from k4s.cli.commands.push import push
from k4s.cli.commands.context import context
from k4s.cli.commands.history import history
from k4s.cli.commands.install import install
from k4s.cli.commands.status import status
from k4s.cli.commands.tls import tls
from k4s.cli.commands.upgrade import upgrade
from k4s.cli.state import CliState
from k4s.core.context_store import ContextStore
from k4s.core.history import HistoryManager
from k4s.core.update_check import check_for_update
from k4s.ui.ui import Ui, UiOptions, Verbosity
from k4s.cli.verbosity import apply_runtime_verbosity_hooks, configure_logging

logging.basicConfig(level=logging.WARNING, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

K4S_BANNER = r"""[bold #3D4F5F]
 ██╗  ██╗[bold #E8763B]██╗  ██╗[/bold #E8763B]███████╗
 ██║ ██╔╝[bold #E8763B]██║  ██║[/bold #E8763B]██╔════╝
 █████╔╝ [bold #E8763B]███████║[/bold #E8763B]╚█████╗
 ██╔═██╗ [bold #E8763B]╚════██║[/bold #E8763B] ╚═══██║
 ██║  ██╗[bold #E8763B]     ██║[/bold #E8763B]██████╔╝
 ╚═╝  ╚═╝[bold #E8763B]     ╚═╝[/bold #E8763B]╚═════╝[/bold #3D4F5F]
"""


# Preserve command registration order in --help output.
class OrderedGroup(click.Group):
    def list_commands(self, ctx):
        return list(self.commands)


def _build_ui(quiet: bool, verbose: int) -> Ui:
    if quiet:
        verbosity = Verbosity.quiet
    else:
        verbosity = {0: Verbosity.normal, 1: Verbosity.logs}.get(verbose, Verbosity.debug)
    return Ui(UiOptions(verbosity=verbosity))


@click.group(cls=OrderedGroup, invoke_without_command=True, context_settings={"help_option_names": ["--help"]})
@click.version_option(package_name="k4s", prog_name="k4s")
@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 k4s(ctx, quiet, verbose):
    """A CLI tool for managing installations and Kubernetes operations."""
    ctx.ensure_object(dict)
    configure_logging()
    ui = _build_ui(quiet=quiet, verbose=verbose)
    apply_runtime_verbosity_hooks(ui)
    ctx.obj["state"] = CliState(ui=ui, contexts=ContextStore(), history=HistoryManager())

    if not quiet:
        update_notice = check_for_update()
        if update_notice:
            ui.console.print(f"[yellow]{update_notice}[/yellow]")
            ui.console.print()

    if ctx.invoked_subcommand is None:
        ui.console.print(K4S_BANNER)
        ui.info(ctx.get_help())


@k4s.command()
@click.pass_context
def init(ctx):
    """Initialize the k4s working environment.

    Creates the ~/.k4s directory structure and shows a quick-start guide.
    Safe to run multiple times.
    """
    state: CliState = ctx.obj["state"]
    ui = state.ui

    ui.console.print(K4S_BANNER)

    base_dir = os.path.expanduser("~/.k4s")
    os.makedirs(base_dir, exist_ok=True)
    ui.success(f"k4s directory ready: {base_dir}")

    ui.info("")
    ui.info("Quick start:")
    ui.info("  1. Add a connection context:")
    ui.info("     VM:   k4s context add prod --host 10.0.1.5 --username ubuntu -i ~/.ssh/id_rsa --current")
    ui.info("     K8s:  k4s context add staging --type k8s --kubeconfig ~/.kube/config --current")
    ui.info("")
    ui.info("  2. Create a cluster or install a product:")
    ui.info("     k4s create cluster --control-plane cp1 --worker w1")
    ui.info("     k4s install nexus                        (VM product)")
    ui.info("     k4s install dataiku --version 13.5.4     (VM product)")
    ui.info("     k4s install starburst --context my-k8s   (Helm/K8s product)")
    ui.info("")
    ui.info("  3. Check status:")
    ui.info("     k4s status nexus")
    ui.info("     k4s status dataiku")
    ui.info("")
    ui.info("Run `k4s --help` to see all available commands.")


# Register commands in logical order (preserved by OrderedGroup).
k4s.add_command(init)          # Getting started
k4s.add_command(context)       # Manage connections
k4s.add_command(create)        # Create clusters and resources (verb-first)
k4s.add_command(cluster)       # Manage existing clusters (status, delete, kubeconfig)
k4s.add_command(install)       # Install products
k4s.add_command(upgrade)       # Upgrade products
k4s.add_command(build)         # Build artifacts
k4s.add_command(push)          # Push artifacts to registries
k4s.add_command(export)        # Export artifacts to remote hosts
k4s.add_command(status)        # Check status
k4s.add_command(tls)           # TLS certificates
k4s.add_command(history)       # Operation history
