"""CLI command for checking product status on a target host."""
import click

from k4s.cli.state import CliState
from k4s.cli.target import resolve_target
from k4s.cli.errors import exit_with_error
from k4s.cli.verbosity import apply_command_ui_overrides
from k4s.core.executor import Executor
from k4s.recipes.dataiku.status import check_status as dataiku_check_status
from k4s.recipes.nexus.status import check_status as nexus_check_status


# Product-specific defaults used when the user omits optional flags.
_PRODUCT_DEFAULTS = {
    "dataiku": {"os_user": "dataiku", "data_dir": "/data/dataiku/DATA_DIR", "port": 10000},
    "nexus": {"os_user": "nexus", "data_dir": "/opt/sonatype-work", "port": 8081},
}


@click.command("status")
@click.argument("product", type=click.Choice(["dataiku", "nexus"], case_sensitive=False))
@click.option("--context", "context_name", default=None, help="Context name (or 'local'). Uses current context if omitted.")
@click.option("--os-user", default=None, help="OS user that owns the installation (default: product-specific).")
@click.option("--data-dir", default=None, help="Product data directory (default: product-specific).")
@click.option("--port", default=None, type=int, help="Product port (default: product-specific).")
@click.option("--check/--no-check", default=False, show_default=True, help="Exit non-zero when health checks fail.")
@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 status(ctx, product, context_name, os_user, data_dir, port, check, quiet, verbose):
    """Check product status on a remote host.

    Connects to the target and runs product-specific health checks.
    Does not require a prior k4s install — works on any host.

    \b
    Examples:
      k4s status dataiku                              # uses current context + defaults
      k4s status dataiku --context prod-vm
      k4s status nexus --context nexus-vm --port 9081
    """
    state: CliState = ctx.obj["state"]
    apply_command_ui_overrides(ctx, state, quiet=quiet, verbose=verbose)
    ui = state.ui
    product = product.lower()

    defaults = _PRODUCT_DEFAULTS.get(product, {})
    os_user = os_user or defaults.get("os_user", "root")
    data_dir = data_dir or defaults.get("data_dir", "/tmp")
    port = port if port is not None else defaults.get("port", 0)

    try:
        c = resolve_target(state, context_name)
        ex = Executor(c.to_server_config())

        with ex:
            if product == "dataiku":
                rep = dataiku_check_status(ui, ex, os_user=os_user, data_dir=data_dir, port=port)
                if check:
                    ok = True
                    if rep.dss_status and "RUNNING" not in rep.dss_status.upper():
                        ok = False
                    if not rep.listening:
                        ok = False
                    if rep.http_code is not None and not (200 <= rep.http_code < 400):
                        ok = False
                    if not ok:
                        ctx.exit(1)

            elif product == "nexus":
                rep = nexus_check_status(ui, ex, os_user=os_user, data_dir=data_dir, port=port)
                if check:
                    ok = True
                    if rep.service_status and "active (running)" not in rep.service_status.lower():
                        ok = False
                    if not rep.listening:
                        ok = False
                    if rep.http_code is not None and not (200 <= rep.http_code < 400):
                        ok = False
                    if not ok:
                        ctx.exit(1)

    except Exception as e:
        exit_with_error(ctx, ui, e, code=1)
