{ pkgs, lib, modulesPath, inputs, ... }:
let
  installScript = pkgs.writeShellScriptBin "nixos-install-host" ''
    set -euo pipefail

    BOLD='\033[1m'
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[1;33m'
    NC='\033[0m'

    header() { echo -e "\n''${BOLD}==> $1''${NC}"; }
    ok()     { echo -e "''${GREEN}[ok]''${NC} $1"; }
    warn()   { echo -e "''${YELLOW}[warn]''${NC} $1"; }
    die()    { echo -e "''${RED}[error]''${NC} $1"; exit 1; }

    FLAKE="path:/etc/nixos-config"

    header "NixOS Installer"
    echo "Available hosts:"
    nix eval "$FLAKE#nixosConfigurations" --apply builtins.attrNames --json 2>/dev/null \
      | ${pkgs.jq}/bin/jq -r '.[]' | grep -v installer | sed 's/^/  /'
    echo ""

    read -p "Host to install: " HOST
    [ -z "$HOST" ] && die "No host specified."

    header "Available disks"
    lsblk -d -o NAME,SIZE,MODEL --noheadings | grep -v loop
    echo ""

    CONFIGURED_DISK=$(nix eval "$FLAKE#nixosConfigurations.$HOST.config.local.notebook.disk" --raw 2>/dev/null \
      || echo "/dev/nvme0n1")
    echo -e "Disk configured for this host: ''${BOLD}$CONFIGURED_DISK''${NC}"
    read -p "Target disk [$CONFIGURED_DISK]: " DISK_INPUT
    DISK="''${DISK_INPUT:-$CONFIGURED_DISK}"

    [ ! -b "$DISK" ] && die "$DISK is not a valid block device."

    if [ "$DISK" != "$CONFIGURED_DISK" ]; then
      warn "Disk $DISK differs from configured $CONFIGURED_DISK."
      warn "Edit modules/_hardware/<host>-disko.nix and rebuild the ISO if it doesn't match."
    fi

    header "Age key (secrets decryption)"
    KEYS_PATH=""

    for candidate in /run/media/nixos/*/keys.txt /run/media/*/keys.txt /tmp/keys.txt; do
      if [ -f "$candidate" ]; then
        KEYS_PATH="$candidate"
        ok "Found at $KEYS_PATH"
        break
      fi
    done

    if [ -z "$KEYS_PATH" ]; then
      warn "Age key not found automatically."
      echo "Options:"
      echo "  1. Copy keys.txt to a USB, mount it, and it will be found at /run/media/*"
      echo "  2. Enter the path manually below"
      read -p "Path to keys.txt: " KEYS_PATH
    fi

    [ ! -f "$KEYS_PATH" ] && die "Age key not found at $KEYS_PATH"

    header "Confirmation"
    echo -e "  Host   : ''${BOLD}$HOST''${NC}"
    echo -e "  Disk   : ''${BOLD}$DISK''${NC} (ALL DATA WILL BE ERASED)"
    echo -e "  Keys   : ''${BOLD}$KEYS_PATH''${NC}"
    echo ""
    read -p "Type 'yes' to continue: " CONFIRM
    [ "$CONFIRM" != "yes" ] && { echo "Aborted."; exit 1; }

    header "Partitioning and formatting"
    echo "(You will be prompted to set the LUKS passphrase.)"
    disko --mode destroy,format,mount --flake "$FLAKE#$HOST"

    header "Copying age key"
    mkdir -p /mnt/etc/sops/age
    install -m 600 "$KEYS_PATH" /mnt/etc/sops/age/keys.txt
    ok "Age key installed."

    header "Installing NixOS"
    nixos-install --root /mnt --flake "$FLAKE#$HOST" --no-root-passwd

    echo ""
    ok "Installation complete! Remove the USB drive and reboot."
  '';
in {
  imports = [
    "${modulesPath}/installer/cd-dvd/installation-cd-minimal.nix"
  ];

  services.getty.autologinUser = lib.mkForce "root";

  nix.settings = {
    experimental-features = [ "nix-command" "flakes" ];
    tarball-ttl            = 0;
  };

  # NetworkManager instead of wpa_supplicant for nmtui support
  networking.networkmanager.enable   = true;
  networking.wireless.enable         = lib.mkForce false;

  environment.systemPackages = [
    installScript
    inputs.disko.packages.${pkgs.stdenv.hostPlatform.system}.default
    pkgs.git
    pkgs.age
    pkgs.sops
    pkgs.jq
    pkgs.neovim
  ];

  # Embed the flake source so the install script can reference it at path:/etc/nixos-config
  environment.etc."nixos-config".source = ../.;

  documentation.enable       = lib.mkForce false;
  documentation.nixos.enable = lib.mkForce false;

  system.stateVersion = "25.11";
}
