{ config, pkgs, lib, ... }:
{
  # Binary cache proxy using ncps (Nix Cache Proxy Server)
  # Transparently caches packages from cache.nixos.org for faster LAN access
  #
  # How it works:
  # - Acts as HTTP proxy for cache.nixos.org
  # - Caches packages on first request
  # - Subsequent requests served from local disk (LAN speed)
  # - No signing needed (packages already signed by upstream)
  # - Automatic fallback to cache.nixos.org if this host is down
  #
  # Setup:
  # 1. Deploy this host
  # 2. Deploy all other hosts (they're already configured to use this)
  # 3. Cache warms up automatically on first use

  services.ncps = {
    enable = true;
    cache = {
      hostName = config.networking.hostName;
      # NOTE: These paths are hardcoded to /persist (not using config.custom.impermanence.persistPath)
      # This is acceptable since this service is only enabled on btrfs-based hosts
      dataPath = "/persist/ncps/data";
      tempPath = "/persist/ncps/tmp";
      databaseURL = "sqlite:/persist/ncps/db/db.sqlite";
      maxSize = "300G";  # Adjust based on available disk space
      lru.schedule = "0 3 * * *";  # Clean up daily at 3 AM if over maxSize
    };
    server.addr = "0.0.0.0:8501";
    upstream = {
      caches = [ "https://cache.nixos.org" ];
      publicKeys = [
        "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="
      ];
    };
  };

  # Open firewall for LAN access
  networking.firewall.allowedTCPPorts = [ 8501 ];
}
