"""Nexus Repository Manager status checks."""
from __future__ import annotations

from dataclasses import dataclass

from k4s.core.executor import Executor
from k4s.recipes.common.run import run
from k4s.ui.ui import Ui


@dataclass(frozen=True)
class NexusStatus:
    """Result of Nexus health checks."""

    service_status: str | None
    listening: bool
    port: int
    http_code: int | None


def _format_service_detail(raw_is_active: str, detail_lines: str) -> str:
    """Build a human-friendly systemd service summary with a colored dot.

    Parses the ``systemctl status`` output to extract the Loaded and
    Active lines, then prepends a colored dot indicator:

    - green ``●`` for ``active (running)``
    - red ``●`` for anything else (inactive, failed, etc.)
    """
    is_running = raw_is_active.strip().lower() == "active"

    dot = "[green]●[/green]" if is_running else "[red]●[/red]"

    # Extract key lines from the full status output.
    loaded_line = ""
    active_line = ""
    for line in detail_lines.splitlines():
        stripped = line.strip()
        if stripped.startswith("Loaded:"):
            loaded_line = stripped
        elif stripped.startswith("Active:"):
            active_line = stripped

    parts: list[str] = []
    if active_line:
        parts.append(f"{dot} {active_line}")
    elif raw_is_active.strip():
        parts.append(f"{dot} {raw_is_active.strip()}")
    else:
        parts.append("[red]●[/red] unknown")

    if loaded_line:
        parts.append(f"  {loaded_line}")

    return "\n".join(parts)


def check_status(ui: Ui, ex: Executor, *, os_user: str, data_dir: str, port: int) -> NexusStatus:
    """Check Nexus Repository Manager status on the target host.

    Checks systemd service state, port listening, and performs a lightweight
    HTTP probe against the Nexus service endpoint.
    """
    # Systemd service status (single word: active / inactive / failed / ...).
    rc, out, err = run(ex, "sudo -n systemctl is-active nexus.service 2>/dev/null || true")
    raw_status = (out or "").strip()
    service_status = raw_status or None

    # Full status output for Loaded / Active lines.
    _, out2, _ = run(ex, "sudo -n systemctl status nexus.service --no-pager -l 2>/dev/null || true")
    detail_lines = out2 or ""

    service_display = _format_service_detail(raw_status, detail_lines)

    # Listening check (best-effort).
    _, out3, _ = run(ex, f"sudo -n ss -ltn 'sport = :{int(port)}' 2>/dev/null || true")
    listening = "LISTEN" in (out3 or "")

    # HTTP probe (best-effort).
    http_code: int | None = None
    curl_cmd = (
        f"curl -sS --connect-timeout 3 --max-time 8 "
        f"-o /dev/null -w %{{http_code}} http://127.0.0.1:{int(port)}/ || true"
    )
    rc4, out4, _ = run(ex, curl_cmd)
    if rc4 == 0 and out4.strip().isdigit():
        code = int(out4.strip())
        if code != 0:
            http_code = code

    # Render summary table.
    rows: list[list[str]] = []
    rows.append(["systemd service", service_display])
    rows.append(["port listening", f"yes (:{port})" if listening else f"no (:{port})"])
    rows.append(["local http code", "-" if http_code is None else str(http_code)])
    ui.table(title="Nexus runtime status", columns=["check", "result"], rows=rows)

    return NexusStatus(
        service_status=service_status,
        listening=listening,
        port=port,
        http_code=http_code,
    )
