"""RHEL/Fedora/CentOS ``ks.cfg`` (kickstart) generation (pure renderer).

Kickstart is Red Hat's automated install format, read by Anaconda
on the installation ISO. VManager generates a minimal kickstart
file from a :class:`ProvisioningInput` and passes it to virt-install
via the ``inst.ks=file:/ks.cfg`` kernel command line; the
``creator/builder`` module wires the injection.

The generated kickstart handles the same core workflow as preseed:
auto-partition the whole disk, create a sudo-enabled user, install
requested packages, set up SSH keys, and run post-install commands.

This module is the **pure** half: :func:`render` returns the
``ks.cfg`` text and performs no I/O. The atomic-write ``generate``
helper is adapter-bound and lives in the legacy
``mgf.vm.provisioning.kickstart`` module.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from mgf.vm.core.provisioning.spec import ProvisioningInput


def render(spec: ProvisioningInput) -> str:
    """Return a ``ks.cfg`` as a single text blob.

    Mirrors the structure documented in Anaconda's kickstart guide:
    header directives, ``%packages`` section, optional ``%post``
    sections for SSH keys and run-commands.
    """
    prov = spec.provisioning
    hostname = prov.hostname or spec.name
    username = prov.username or "vmanager"
    password = prov.password or "vmanager"

    lines: list[str] = [
        "# Generated by vmanager — do not edit by hand",
        "",
        "text",
        "reboot",
        "lang en_US.UTF-8",
        "keyboard us",
        "timezone UTC --isUtc",
        f"network --bootproto=dhcp --device=link --activate --hostname={hostname}",
        "",
        "# Installation source: the install media itself",
        "cdrom",
        "",
        "# Partitioning",
        "zerombr",
        "clearpart --all --initlabel",
        "autopart --type=lvm",
        "bootloader --location=mbr",
        "",
        "# Accounts",
        "rootpw --lock",
        f"user --name={username} --password={password} --plaintext "
        f"--groups=wheel --gecos={username}",
        "",
        "# Firewall / SELinux",
        "firewall --enabled --ssh",
        "selinux --enforcing",
        "services --enabled=NetworkManager,sshd,chronyd",
    ]

    # %packages section.
    lines.extend(["", "%packages", "@core", "openssh-server", "sudo"])
    if prov.packages:
        lines.extend(prov.packages)
    lines.append("%end")

    # SSH keys land in a %post section.
    if prov.ssh_authorized_keys:
        lines.extend(
            [
                "",
                "%post --log=/root/ks-post-ssh.log",
                f"mkdir -p /home/{username}/.ssh",
                f"cat > /home/{username}/.ssh/authorized_keys <<'__VM_KEYS__'",
                *prov.ssh_authorized_keys,
                "__VM_KEYS__",
                f"chown -R {username}:{username} /home/{username}/.ssh",
                f"chmod 700 /home/{username}/.ssh",
                f"chmod 600 /home/{username}/.ssh/authorized_keys",
                "%end",
            ]
        )

    # Run-commands land in a second %post section so ordering is
    # predictable (SSH keys first, user commands second).
    if prov.run_commands:
        lines.extend(["", "%post --log=/root/ks-post-runcmd.log"])
        lines.extend(prov.run_commands)
        lines.append("%end")

    return "\n".join(lines) + "\n"


__all__ = ["render"]
