# Live ISO host — boot the full Nomarchy desktop from a USB stick or QEMU
# without touching the disk. The live session bundles nomarchy-install
# (gum + disko + mkFlake) for a real install; this target also lets you
# test the distro end-to-end on real hardware before committing to disk.
{ lib, pkgs, username, nomarchySrc, ... }:

let
  # ISO boot branding: the Nomarchy monogram recolored to the palette accent,
  # centred on the theme base. Built from the vendored vector logo and the
  # live theme-state.json (Boreal by default). The same composed image
  # backs both the isolinux (BIOS) splash and the GRUB (UEFI) theme below, so
  # the two boot paths match.
  state = builtins.fromJSON (builtins.readFile ../theme-state.json);
  isoColor = key: fallback: lib.removePrefix "#" ((state.colors or { }).${key} or fallback);
  accent = isoColor "accent" "B79BE8";
  base = isoColor "base" "21272F";
  subtext = isoColor "subtext" "97A3B2";

  isoSplash = pkgs.runCommand "nomarchy-iso-splash.png"
    { nativeBuildInputs = [ pkgs.imagemagick pkgs.librsvg ]; } ''
    rsvg-convert -h 320 ${../modules/nixos/branding/logo.svg} > logo.png
    magick logo.png -fill "#${accent}" -colorize 100 logo-c.png
    magick -size 1920x1080 xc:"#${base}" \
      logo-c.png -gravity center -composite $out
  '';

  # GRUB (UEFI) theme matched to the BIOS splash: the same accent-logo-on-base
  # image as the background, plus a palette-coloured boot menu in the lower
  # third (clear of the centred logo). Derived from nixos-grub2-theme only to
  # reuse its bundled DejaVu .pf2 font — we overwrite the background and
  # theme.txt and drop the stock NixOS logo (ours is in the background). grub
  # loads every .pf2 in the dir, so "DejaVu Regular" resolves.
  grubThemeTxt = pkgs.writeText "nomarchy-grub-theme.txt" ''
    title-text: ""
    desktop-image: "background.png"
    desktop-color: "#${base}"

    message-font: "DejaVu Regular"
    message-color: "#${subtext}"
    terminal-font: "DejaVu Regular"

    + boot_menu {
      left = 50%-300
      width = 600
      top = 64%
      height = 26%
      item_font = "DejaVu Regular"
      item_color = "#${subtext}"
      item_height = 36
      item_spacing = 6
      selected_item_font = "DejaVu Regular"
      selected_item_color = "#${accent}"
      scrollbar = false
    }

    + progress_bar {
      id = "__timeout__"
      left = 50%-300
      top = 92%
      width = 600
      height = 16
      show_text = true
      text = "@TIMEOUT_NOTIFICATION_MIDDLE@"
      font = "DejaVu Regular"
      text_color = "#${subtext}"
      border_color = "#${accent}"
      bg_color = "#${base}"
      fg_color = "#${accent}"
    }
  '';

  nomarchyGrubTheme = pkgs.runCommand "nomarchy-grub-theme" { } ''
    cp -r ${pkgs.nixos-grub2-theme} $out
    chmod -R u+w $out
    cp ${isoSplash} $out/background.png
    cp ${grubThemeTxt} $out/theme.txt
    rm -f $out/logo.png
  '';
in
{
  networking.hostName = "nomarchy-live";

  isoImage.volumeID = lib.mkForce "NOMARCHY_LIVE";
  isoImage.edition = lib.mkForce "live";
  isoImage.splashImage = isoSplash; # isolinux / BIOS
  isoImage.grubTheme = nomarchyGrubTheme; # GRUB / UEFI

  # The minimal-CD profile slims the image for a CONSOLE installer; this
  # ISO is the desktop, so re-enable what it strips. Above all
  # fontconfig (upstream forces it off at mkOverride 500): without it
  # no configured family resolves — Waybar icons render as tofu and
  # Ghostty silently falls back to the wrong font (seen on the
  # Latitude 5410). Normal priority (100) beats the override.
  fonts.fontconfig.enable = true;

  # No boot splash on the install medium: the installer ISO boots its
  # own initrd path (squashfs), and visibility of boot messages is
  # worth more than polish here. Installed systems get the splash.
  nomarchy.system.plymouth.enable = false;
  xdg.icons.enable = true;
  xdg.mime.enable = true;
  xdg.autostart.enable = true;
  documentation.enable = true;
  documentation.man.enable = true;

  # Do NOT touch networking.wireless here: since NixOS 26.05 the
  # NetworkManager module drives its wifi backend through it
  # (wireless.enable = true + dbusControlled). Force-disabling it
  # kills NM's supplicant — wifi devices vanish from nmtui even
  # though the driver is loaded (seen on a Latitude 5410 / AX201).

  # ── Live user: no password, straight into the desktop ──────────────
  users.users.${username} = {
    isNormalUser = true;
    initialHashedPassword = "";
    extraGroups = [ "wheel" "networkmanager" "video" "render" "audio" "input" ];
  };
  security.sudo.wheelNeedsPassword = false;
  services.getty.autologinUser = lib.mkForce username;

  # Boot straight into Hyprland once; logging out lands on tuigreet.
  services.greetd.settings.initial_session = {
    command = "start-hyprland";
    user = username;
  };

  # ── Hardware breadth ────────────────────────────────────────────────
  # Force-loading every GPU driver in the initrd (amdgpu+radeon+nouveau+
  # i915) panics most machines — only one of them can claim the GPU and
  # the others explode. `availableKernelModules` lets udev load just the
  # one that matches; virtio_gpu covers QEMU (tools/test-live-iso.sh).
  boot.initrd.availableKernelModules = [ "amdgpu" "radeon" "nouveau" "i915" "virtio_gpu" ];
  services.qemuGuest.enable = lib.mkDefault true;

  # ── The Nomarchy flake on board ─────────────────────────────────────
  # Read-only copy in /etc (also pins the flake source into the ISO
  # closure); seeded writable into the live home so theme switching —
  # state write + `home-manager switch` — works exactly like on an
  # installed system. $NOMARCHY_PATH already defaults to ~/.nomarchy.
  environment.etc."nomarchy".source = nomarchySrc;

  systemd.services.nomarchy-seed-flake = {
    description = "Seed a writable Nomarchy flake into the live user's home";
    wantedBy = [ "multi-user.target" ];
    serviceConfig.Type = "oneshot";
    script = ''
      home=/home/${username}
      if [ ! -e "$home/.nomarchy" ]; then
        cp -r ${nomarchySrc} "$home/.nomarchy"
        chmod -R u+w "$home/.nomarchy"
        chown -R ${username}:users "$home/.nomarchy"
      fi
    '';
  };

  services.getty.helpLine = lib.mkForce ''

    Welcome to the Nomarchy live environment.

    The graphical session autologins as '${username}' (no password).
    Theme switching:  nomarchy-theme-sync apply <name>   (or SUPER+T)
    Wallpapers:       nomarchy-theme-sync bg next        (or SUPER+SHIFT+T)
    Install to disk:  nomarchy-install
    The flake lives at ~/.nomarchy.
  '';

  # ── Live-session desktop tweaks ─────────────────────────────────────
  home-manager.users.${username} = {
    # No idle lock/suspend on the install medium: an offline install
    # runs 20-30 min unattended, and hypridle would blank the display
    # then SUSPEND the machine mid-install (it did — the install-hung
    # regression). Installed systems keep idle management.
    nomarchy.idle.enable = false;

    # Durable install affordance (BACKLOG #57): always-visible desktop
    # entry, not only the 3s toast / getty helpLine / tribal knowledge.
    # Tools › Install Nomarchy is self-gated on this package in rofi.nix.
    xdg.desktopEntries.nomarchy-install = {
      name = "Install Nomarchy";
      genericName = "Installer";
      comment = "Install Nomarchy to this machine's disk";
      exec = "nomarchy-install";
      terminal = true;
      icon = "system-software-install";
      categories = [ "System" "Settings" ];
      startupNotify = true;
    };

    wayland.windowManager.hyprland.settings = {
      # QEMU (and some panels) report a tiny "preferred" mode; ask for
      # the highest resolution instead.
      monitor = lib.mkForce [ ",highres,auto,1" ];
      # Welcome toast once the session is up (concatenated onto the
      # base exec-once list).
      exec-once = [
        "sh -c 'sleep 3; notify-send -a Nomarchy \"Welcome to Nomarchy\" \"SUPER+Return terminal · SUPER+T themes · Install Nomarchy app or nomarchy-install\"'"
      ];
    };
  };

  system.stateVersion = "26.05";
}
