{ pkgs }:
let
  lib = pkgs.lib;
in
pkgs.stdenv.mkDerivation rec {
  pname = "flynn";
  version = "0.1.0";

  # Keep the source small and deterministic for Nix builds.
  src = lib.cleanSourceWith {
    src = ../.;
    filter =
      path: type:
      let
        baseName = baseNameOf path;
      in
      !(
        baseName == ".git"
        || baseName == "node_modules"
        || baseName == "dist"
        || baseName == ".worktrees"
        || baseName == "whisper-models"
      );
  };

  pnpmDeps = pkgs.fetchPnpmDeps {
    inherit pname version src;
    fetcherVersion = 1;

    # NOTE: Update this hash after the first `nix build` by copying the
  # "got: sha256-..." value from the error message.
    hash = "sha256-dyxGSSLoMVEKgTs+owdgRZw9uvJhQLEFsib/GPyxtxM=";
  };

  nativeBuildInputs = [
    pkgs.nodejs_22
    pkgs.pnpm
    pkgs.pnpmConfigHook
    pkgs.makeWrapper
    pkgs.python3
    pkgs.gnumake
    pkgs.gcc
    pkgs.pkg-config
  ];

  buildPhase = ''
    runHook preBuild
    pnpm build
    runHook postBuild
  '';

  installPhase = ''
    runHook preInstall

    mkdir -p $out/lib/flynn
    cp -r dist node_modules package.json config $out/lib/flynn/
    if [ -f SOUL.md ]; then
      cp SOUL.md $out/lib/flynn/
    fi

    makeWrapper ${pkgs.nodejs_22}/bin/node $out/bin/flynn \
      --add-flags $out/lib/flynn/dist/cli/index.js \
      --set-default NODE_ENV production

    runHook postInstall
  '';

  meta = with lib; {
    description = "Self-hosted personal AI agent";
    homepage = "https://github.com/will666/flynn";
    license = licenses.mit;
    platforms = platforms.unix;
    mainProgram = "flynn";
  };
}
