{
  config,
  pkgs,
  lib,
  ...
}: let
  choose = paths: builtins.head (builtins.filter (p: builtins.pathExists p) paths);

  # Dummy filesystem config for dry-run evaluation
  dummyFileSystems = {
    fileSystems."/" = {
      device = "/dev/disk/by-label/nixos";
      fsType = "ext4";
    };
  };
in {
  options.local = {
    hostname = lib.mkOption {
      type = lib.types.str;
      default = "nixos-build-machine";
      description = "System hostname";
    };
    username = lib.mkOption {
      type = lib.types.str;
      default = "nixosbm";
      description = "Primary user username";
    };
    userDescription = lib.mkOption {
      type = lib.types.str;
      default = "NixOS Build Machine";
      description = "Primary user description";
    };
    address = lib.mkOption {
      type = lib.types.str;
      default = "10.1.1.3";
      description = "Static IP address";
    };
  };

  imports =
    [
      (choose [./modules/local/hostname_username.nix ../local/hostname_username.nix])
      (choose [./modules/local/networking_local.nix ../local/networking_local.nix])
      (choose [./modules/lix-default.nix ../lix-default.nix])
      (choose [./modules/toolsets/grafana_metric.nix ../toolsets/grafana_metric.nix])
      (choose [./modules/secrets-config/sops-build-machine.nix ../secrets-config/sops-build-machine.nix])
      ## TODO: Make this more elegant and less risky for unexpected errors happening.
    ]
    ++ lib.optional (builtins.pathExists ./hardware-configuration.nix) ./hardware-configuration.nix
    ++ lib.optional (!builtins.pathExists ./hardware-configuration.nix) dummyFileSystems;

  config = {
    # Local metadata
    local.hostname = "nixos-build-machine";
    local.username = "nixosbm";
    local.userDescription = "NixOS Build Machine";
    local.address = "10.1.1.3";

    # Enable Rsync
    services.rsync.enable = true;

    # Passwordless sudo for wheel group
    security.sudo.wheelNeedsPassword = false;

    # Hardware U2F support - Passwordless sudo with hardware key
    security.pam.u2f = {
      enable = true;
      settings = {
        authfile = "/etc/u2f_keys";
        cue = true;
        pinverification = 0; # No PIN verification
        userpresence = 1; # Require user presence (touch)
      };
    };

    # Optimize builds
    nix.settings = {
      # Enable parallel building
      max-jobs = "auto";
      cores = 0; # Use all available cores

      # Optimize store operations
      auto-optimise-store = true;

      # Build settings
      sandbox = true;
      keep-outputs = true;
      keep-derivations = true;
    };

    # Enable distributed builds (optional, for your VM setup)
    nix.buildMachines = [];
    nix.distributedBuilds = false;

    # Optimize garbage collection
    nix.gc = {
      automatic = true;
      dates = "weekly";
      options = "--delete-older-than 30d";
    };

    # Increase build speed with tmpfs for builds (if you have enough RAM)
    # Comment out if low on memory
    systemd.services.nix-daemon.environment = {
      TMPDIR = "/tmp";
    };
    boot.tmp.useTmpfs = true;
    boot.tmp.tmpfsSize = "50%"; # Adjust based on your 62GB RAM

    # SSH Agent authentication
    security.pam.sshAgentAuth.enable = true;

    # Automatic upgrades
    system.autoUpgrade = {
      enable = true; # Set to true for automatic updates
      dates = "daily";
      allowReboot = false;
    };

    # Bootloader fallback settings are provided by the seabios import
    # (seabios-assigned-iso-at-birth.nix)

    # Replicate systemd-boot configuration from the deprecated configuration
    # so the system is bootable (matches build-deprecated/configuration.nix).
    boot.loader.systemd-boot.enable = true;
    boot.loader.efi.canTouchEfiVariables = true;

    # Enable Tailscale
    services.tailscale.enable = true;

    # Define a user account. Don't forget to set a password with ‘passwd’.
    users.users.nixosbm = {
      isNormalUser = true;
      description = "NixOS Build Machine";
      extraGroups = ["networkmanager" "wheel"];
      packages = with pkgs; [];
    };

    # Remote builder server setup
    users.users.nixremote = {
      isNormalUser = true;
      description = "Nix Remote Builder";
      home = "/home/nixremote";
      createHome = true;

      # SSH key for remote builds
      openssh.authorizedKeys.keys = [
        # Add the public key from your client machines here
        # Example: "ssh-ed25519 AAAAC3... root@client-machine"
      ];
    };

    systemd.tmpfiles.rules = [
      "z /home/nixremote 0555 nixremote nixremote - -"
      "z /home/nixremote/.ssh 0555 nixremote nixremote - -"
    ];

    # Allow unfree packages
    nixpkgs.config.allowUnfree = true;

    # List packages installed in system profile. To search, run:
    # $ nix search wget
    environment.systemPackages = with pkgs; [
      wget
      fastfetch
      hyfetch
      helix
    ];

    programs.gnupg.agent = {
      enable = true;
      enableSSHSupport = true;
    };

    # Enable the OpenSSH daemon.
    services.openssh.enable = true;

    # Enable Podman for Gitea Actions Runner
    virtualisation.podman = {
      enable = true;
      dockerCompat = true;
      defaultNetwork.settings.dns_enabled = true;
    };

    # Network configuration for the build machine on the Proxmox bridge
    networking.interfaces.ens18.ipv4.addresses = [
      {
        address = config.local.address;
        #dns = "10.1.1.2";
        prefixLength = 24;
      }
    ];
    networking.defaultGateway = "10.1.1.1";
    environment.etc."resolv.conf".text = ''
      nameserver 10.1.1.2
    '';

    services.gitea-actions-runner = {
      package = pkgs.forgejo-runner;
      instances.default = {
        enable = true;
        name = "monolith";
        url = "https://git.prg-radio.org";
        # Obtaining the path to the runner token file may differ
        # tokenFile should be in format TOKEN=<secret>, since it's EnvironmentFile for systemd
        tokenFile = config.sops.secrets.runner_token.path;
        labels = [
          "docker:docker://docker"
          "lix:docker://git.lix.systems/lix-project/lix:latest"
          "nix:docker://git.lix.systems/lix-project/lix:latest"
          "ubuntu-bleeding-edge:docker://ubuntu:resolute"
          "ubuntu-latest:docker://ubuntu:plucky"
          "ubuntu-24.04:docker://ubuntu:noble"
          "alpine:docker://alpine:edge"
          "rust:docker://rust:trixie"
          "python-315:docker://python:3.15.0a6-slim-trixie"
        ];
      };
    };

    # This value determines the NixOS release from which the default
    # settings for stateful data, like file locations and database versions
    # on your system were taken. It‘s perfectly fine and recommended to leave
    # this value at the release version of the first install of this system.
    # Before changing this value read the documentation for this option
    # (e.g. man configuration.nix or on https://nixos.org/nixos/options.html).
    system.stateVersion = "25.11"; # Did you read the comment?

    # Helpful commented examples for remote-build configuration retained from original
    # THE FOLLOWING CODE BLOCK IS FOR COPYING TO OTHER CONFIGURATIONS, NOT FOR THIS FILE
    #  nix.distributedBuilds = true;
    #  nix.buildMachines = [
    #    {
    #      hostName = "nixos-build-machine";
    #      system = "x86_64-linux";
    #      sshUser = "nixremote";
    #      sshKey = "/root/.ssh/nixremote";
    #      maxJobs = 4;
    #      speedFactor = 2;
    #          supportedFeatures = [ "nixos-test" "benchmark" "big-parallel" "kvm" ];
    #    }
    #  ];
    #
    # Generate SSH key for remote building
    #systemd.services.generate-nixremote-key = {
    #  description = "Generate SSH key for remote Nix builds";
    #  wantedBy = [ "multi-user.target" ];
    #  serviceConfig = {
    #    Type = "oneshot";
    #    RemainAfterExit = true;
    #  };
    #  script = ''
    #    if [ ! -f /root/.ssh/nixremote ]; then
    #      ${pkgs.openssh}/bin/ssh-keygen -t ed25519 -f /root/.ssh/nixremote -N "" -C "nix-remote-builder"
    #    fi
    #  '';
    #};
    #
    #programs.ssh.extraConfig = ''
    #  Host nixos-build-machine
    #    HostName 192.168.1.175
    #    IdentitiesOnly yes;
    #    IdentityFile /root/.ssh/nixremote
    #    User nixremoteStrictHostKeyChecking accept-new
    #'';
    #
    # Manual step required: After rebuilding the client, copy /root/.ssh/nixremote.pub
    # from the client to the build machine's users.users.nixremote.openssh.authorizedKeys.keys list,
    # then rebuild the build machine.
    # i.e on the client: run "cat /root.ssh/nixremote.pub"
    # and copy the output to the build machine's configuration.nix
  };
}
