from __future__ import annotations

from k4s.core.executor import Executor
from k4s.recipes.common.run import check, q, run


def ensure_apt_updated(ex: Executor) -> None:
    check(ex, "sudo -n apt-get update -y")


def apt_install(ex: Executor, packages: list[str]) -> None:
    pkgs = " ".join(q(p) for p in packages)
    check(ex, f"sudo -n DEBIAN_FRONTEND=noninteractive apt-get install -y {pkgs}")


def ensure_group(ex: Executor, group: str) -> None:
    # idempotent: groupadd returns non-zero if exists; treat that as OK
    rc, _, _ = run(ex, f"sudo -n getent group {q(group)} >/dev/null 2>&1 || sudo -n groupadd {q(group)}")
    if rc != 0:
        # re-run to surface stderr
        check(ex, f"sudo -n groupadd {q(group)}", error_hint="Group creation failed.")


def ensure_user(ex: Executor, *, user: str, group: str) -> None:
    cmd = (
        f"sudo -n id -u {q(user)} >/dev/null 2>&1 || "
        f"sudo -n useradd -m -g {q(group)} -s /bin/bash {q(user)}"
    )
    rc, _, _ = run(ex, cmd)
    if rc != 0:
        check(ex, f"sudo -n useradd -m -g {q(group)} -s /bin/bash {q(user)}", error_hint="User creation failed.")


def ensure_dir_owned(ex: Executor, path: str, *, owner: str, group: str, mode: str | None = None) -> None:
    check(ex, f"sudo -n mkdir -p {q(path)}")
    check(ex, f"sudo -n chown -R {q(owner)}:{q(group)} {q(path)}")
    if mode:
        check(ex, f"sudo -n chmod {q(mode)} {q(path)}")


def ensure_user_in_group(ex: Executor, *, user: str, group: str) -> None:
    # idempotent: usermod -aG always succeeds; membership takes effect on next login
    check(ex, f"sudo -n usermod -aG {q(group)} {q(user)}")


def detect_ubuntu_like(ex: Executor) -> bool:
    rc, out, _ = run(ex, "cat /etc/os-release 2>/dev/null | grep -E '^ID=' || true")
    return rc == 0 and ("ubuntu" in out or "debian" in out)


def install_kubectl(ex: Executor) -> None:
    """Install kubectl via the official Kubernetes apt repository (idempotent)."""
    rc, _, _ = run(ex, "command -v kubectl >/dev/null 2>&1", silent=True)
    if rc == 0:
        return  # already installed

    check(ex, "sudo -n install -m 0755 -d /etc/apt/keyrings")
    check(
        ex,
        "curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.31/deb/Release.key "
        "| sudo -n gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg --yes",
    )
    check(ex, "sudo -n chmod a+r /etc/apt/keyrings/kubernetes-apt-keyring.gpg")
    check(
        ex,
        "echo 'deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] "
        "https://pkgs.k8s.io/core:/stable:/v1.31/deb/ /' "
        "| sudo -n tee /etc/apt/sources.list.d/kubernetes.list > /dev/null",
    )
    ensure_apt_updated(ex)
    apt_install(ex, ["kubectl"])

