"""``ilum doctor`` command."""

from __future__ import annotations

import typer

import ilum.cli.output as output_mod
from ilum.cli.completers import complete_check_names
from ilum.cli.defaults import resolve_profile_defaults
from ilum.core.helm import HelmClient
from ilum.core.kubernetes import KubeClient
from ilum.doctor.checks import CheckStatus
from ilum.doctor.runner import DoctorRunner


def doctor(
    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."
    ),
    release: str | None = typer.Option(
        None, "--release", "-r", show_default="from profile", help="Helm release name."
    ),
    check: str | None = typer.Option(
        None,
        "--check",
        "-c",
        help="Run a single check by name.",
        autocompletion=complete_check_names,
    ),
    failures_only: bool = typer.Option(
        False, "--failures-only", help="Show only FAIL and WARN results."
    ),
    fix: bool = typer.Option(False, "--fix", help="Attempt to fix simple issues automatically."),
) -> None:
    """Run health checks on the ilum installation."""
    release, namespace, context = resolve_profile_defaults(release, namespace, context)
    console = output_mod.console
    helm = HelmClient(kubecontext=context, namespace=namespace)
    k8s = KubeClient(kubecontext=context)

    # Load enabled modules from the active profile for resource estimation
    modules: list[str] = []
    try:
        from ilum.config.manager import ConfigManager
        from ilum.config.paths import IlumPaths

        cfg = ConfigManager(IlumPaths.default()).load()
        profile = cfg.profiles.get(cfg.active_profile)
        if profile:
            modules = profile.enabled_modules
    except Exception:  # noqa: BLE001
        pass

    runner = DoctorRunner(
        helm=helm, k8s=k8s, console=console, namespace=namespace, release=release, modules=modules
    )

    from ilum.cli.formatters import CommandResult, OutputFormat, ResultFormatter

    fmt = OutputFormat(console.output_format)

    if check:
        result = runner.run_single(check)
        if result is None:
            console.error(f"Unknown check: {check}")
            raise typer.Exit(code=1)

        if fmt != OutputFormat.TABLE:
            cmd_result = CommandResult(
                data=runner.to_dict([result]),
                summary=f"{result.name}: {result.status.value}",
            )
            ResultFormatter().format(cmd_result, fmt, console)

        if result.status == CheckStatus.FAIL:
            raise typer.Exit(code=1)
        return

    results = runner.run_all(render=fmt == OutputFormat.TABLE)

    # Apply --fix
    if fix:
        fixed = runner.fix_simple_issues(results)
        for msg in fixed:
            console.success(f"Fixed: {msg}")

    # Filter for --failures-only
    if failures_only:
        results = [r for r in results if r.status in (CheckStatus.FAIL, CheckStatus.WARN)]

    # Machine-readable output
    if fmt != OutputFormat.TABLE:
        cmd_result = CommandResult(
            data=runner.to_dict(results),
            summary=f"{len(results)} checks",
        )
        ResultFormatter().format(cmd_result, fmt, console)
    elif failures_only:
        # Re-render filtered results for table mode
        runner._render(results)

    if any(r.status == CheckStatus.FAIL for r in results):
        raise typer.Exit(code=1)
