"""Debian/Ubuntu ``preseed.cfg`` generation (pure renderer).

Preseed is Debian's ISO-boot automation format — a key-value file
that the Debian installer (``debian-installer`` / ``d-i``) reads to
answer every prompt it would otherwise put on screen. VManager
generates the file from a :class:`ProvisioningInput` and passes it
to virt-install via ``--initrd-inject`` so the installer reads it
on first boot without needing a network preseed URL.

The set of preseed keys here is deliberately small — the values
that matter for first-boot automation. Users who need advanced
preseed behaviour can write their own file and skip the generator
by setting ``provisioning.backend = "none"`` and passing the file
by hand.

This module is the **pure** half: :func:`render` returns the
``preseed.cfg`` text and performs no I/O. The atomic-write
``generate`` helper that lands the file on disk is adapter-bound and
lives in the legacy ``mgf.vm.provisioning.preseed`` 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 ``preseed.cfg`` as a single text blob.

    The structure matches Debian's ``preseed.cfg`` grammar exactly:
    one ``<owner> <question> <type> <value>`` line per setting, with
    the ``d-i`` owner for installer questions.
    """
    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",
        "",
        "# Locale and keyboard",
        "d-i debian-installer/locale string en_US.UTF-8",
        "d-i keyboard-configuration/xkb-keymap select us",
        "",
        "# Network",
        "d-i netcfg/choose_interface select auto",
        f"d-i netcfg/get_hostname string {hostname}",
        "d-i netcfg/get_domain string localdomain",
        "",
        "# Mirror",
        "d-i mirror/country string manual",
        "d-i mirror/http/hostname string archive.ubuntu.com",
        "d-i mirror/http/directory string /ubuntu",
        "",
        "# Accounts",
        "d-i passwd/root-login boolean false",
        "d-i passwd/make-user boolean true",
        f"d-i passwd/user-fullname string {username}",
        f"d-i passwd/username string {username}",
        f"d-i passwd/user-password password {password}",
        f"d-i passwd/user-password-again password {password}",
        "d-i user-setup/allow-password-weak boolean true",
        "",
        "# Clock and time zone",
        "d-i clock-setup/utc boolean true",
        "d-i time/zone string UTC",
        "d-i clock-setup/ntp boolean true",
        "",
        "# Partitioning — whole disk, guided",
        "d-i partman-auto/method string regular",
        "d-i partman-lvm/device_remove_lvm boolean true",
        "d-i partman-md/device_remove_md boolean true",
        "d-i partman-auto/choose_recipe select atomic",
        "d-i partman-partitioning/confirm_write_new_label boolean true",
        "d-i partman/choose_partition select finish",
        "d-i partman/confirm boolean true",
        "d-i partman/confirm_nooverwrite boolean true",
        "",
        "# Package selection",
        "tasksel tasksel/first multiselect standard",
    ]

    if prov.packages:
        lines.append(f"d-i pkgsel/include string {' '.join(prov.packages)}")

    lines.extend(
        [
            "",
            "# Boot loader",
            "d-i grub-installer/only_debian boolean true",
            "d-i grub-installer/with_other_os boolean true",
            "d-i grub-installer/bootdev string default",
            "",
            "# Finish install",
            "d-i finish-install/reboot_in_progress note",
        ]
    )

    if prov.ssh_authorized_keys:
        # Write keys via a late_command so they land in the new user's
        # ~/.ssh/authorized_keys after first-stage install completes.
        keys_joined = "\\n".join(prov.ssh_authorized_keys)
        lines.extend(
            [
                "",
                "# SSH keys for the default user",
                "d-i preseed/late_command string \\",
                f"  in-target mkdir -p /home/{username}/.ssh && \\",
                f'  in-target sh -c \'printf "{keys_joined}\\n" '
                f"> /home/{username}/.ssh/authorized_keys' && \\",
                f"  in-target chown -R {username}:{username} /home/{username}/.ssh && \\",
                f"  in-target chmod 700 /home/{username}/.ssh && \\",
                f"  in-target chmod 600 /home/{username}/.ssh/authorized_keys",
            ]
        )

    if prov.run_commands:
        lines.extend(
            [
                "",
                "# Post-install commands",
            ]
        )
        for cmd in prov.run_commands:
            lines.append(f"d-i preseed/run string {cmd}")

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


__all__ = ["render"]
