"""``ilum uninstall`` command."""

from __future__ import annotations

import typer

import ilum.cli.output as output_mod
from ilum.cli.defaults import resolve_profile_defaults
from ilum.config.manager import ConfigManager
from ilum.config.paths import IlumPaths
from ilum.core.helm import HelmClient
from ilum.core.kubernetes import KubeClient
from ilum.core.modules import ModuleResolver
from ilum.core.release import ReleaseManager, ReleasePlan
from ilum.errors import IlumError
from ilum.wizard.deps import ensure_tools


def uninstall(
    release: str | None = typer.Option(
        None, "--release", "-r", show_default="from profile", help="Helm release name."
    ),
    namespace: str | None = typer.Option(
        None, "--namespace", "-n", show_default="from profile", help="Kubernetes namespace."
    ),
    context: str | None = typer.Option(
        None, "--context", show_default="from profile", help="Kubernetes context."
    ),
    yes: bool = typer.Option(False, "--yes", "-y", help="Skip confirmation prompt."),
    dry_run: bool = typer.Option(False, "--dry-run", help="Preview without executing."),
    delete_data: bool = typer.Option(
        False,
        "--delete-data",
        help="Delete PersistentVolumeClaims after uninstall.",
    ),
    delete_namespace: bool = typer.Option(
        False,
        "--delete-namespace",
        help="Delete the namespace after uninstall.",
    ),
) -> None:
    """Uninstall the Ilum platform."""
    release, namespace, context = resolve_profile_defaults(release, namespace, context)
    console = output_mod.console

    try:
        ensure_tools(["helm"], console, interactive=not yes)
        paths = IlumPaths.default()
        paths.ensure_dirs()
        mgr = ReleaseManager(
            helm=HelmClient(kubecontext=context, namespace=namespace),
            k8s=KubeClient(kubecontext=context),
            resolver=ModuleResolver(),
            config_mgr=ConfigManager(paths),
            paths=paths,
        )

        # Idempotent: exit 0 if release doesn't exist
        if not mgr.release_exists(release):
            console.info(f"Release '{release}' not found — nothing to uninstall.")
            return

        # Build plan early so we can preview the command
        plan = ReleasePlan(
            action="uninstall",
            release=release,
            namespace=namespace,
            chart="",
        )

        # Summary
        summary_rows = [
            ["Release", release],
            ["Namespace", namespace],
            ["Delete PVCs", "Yes" if delete_data else "No"],
            ["Delete Namespace", "Yes" if delete_namespace else "No"],
        ]
        console.operation_summary(summary_rows, title="Uninstall Summary")
        if delete_data:
            console.warning("PersistentVolumeClaims will be DELETED.")
        if delete_namespace:
            console.warning(f"Namespace '{namespace}' will be DELETED.")

        console.command_preview(mgr.preview_command(plan))

        if dry_run:
            console.info("Dry-run mode — no changes applied.")
            return

        # Confirmation
        if not yes:
            if delete_data or delete_namespace:
                typed = console.prompt_text(
                    f"Type the release name [bold]{release}[/bold] to confirm"
                )
                if typed != release:
                    console.error("Release name does not match. Aborted.")
                    raise typer.Exit(code=1)
            elif not console.confirm("Proceed with uninstall?"):
                console.info("Aborted.")
                raise typer.Exit()

        # Uninstall
        with console.status_spinner("Uninstalling Ilum..."):
            mgr.execute(plan)
        console.success(f"Release '{release}' uninstalled.")

        # Optionally delete PVCs
        if delete_data:
            with console.status_spinner("Deleting PersistentVolumeClaims..."):
                deleted = mgr.k8s.delete_pvcs(namespace)
            if deleted:
                console.success(f"Deleted {len(deleted)} PVC(s): {', '.join(deleted)}")
            else:
                console.info("No PVCs found to delete.")

        # Optionally delete namespace
        if delete_namespace:
            with console.status_spinner(f"Deleting namespace '{namespace}'..."):
                mgr.k8s.delete_namespace(namespace)
            console.success(f"Namespace '{namespace}' deleted.")

        # Clear config
        mgr.save_enabled_modules([], release=release)

    except IlumError as exc:
        console.handle_error(exc)
        raise typer.Exit(code=1) from exc
