{ lib
, stdenv
, fetchurl
, patchelf
, glibc
, makeWrapper
}:

let
  version = "0.55.4";

  srcs = {
    aarch64-darwin = {
      url = "https://github.com/badlogic/pi-mono/releases/download/v${version}/pi-darwin-arm64.tar.gz";
      sha256 = "0vsav9frvnzskk6p6j60i7klrs3m8lphhyi4c39mv2mvhpm8fkl5";
    };
    x86_64-darwin = {
      url = "https://github.com/badlogic/pi-mono/releases/download/v${version}/pi-darwin-x64.tar.gz";
      sha256 = "1377rvhsiiww1bbpgv2v46fjm7iz2smmh8g2yhm28kbsq3gwvvr0";
    };
    x86_64-linux = {
      url = "https://github.com/badlogic/pi-mono/releases/download/v${version}/pi-linux-x64.tar.gz";
      sha256 = "1wnfwnkfq5ffz6wyqyhciv4lz06bpxims0hv0dlhz0f9vliyc1md";
    };
    aarch64-linux = {
      url = "https://github.com/badlogic/pi-mono/releases/download/v${version}/pi-linux-arm64.tar.gz";
      sha256 = "00fp37hgjl40kc59jfpv189i7np53ymm037hvds6k9y2sz818wjy";
    };
  };

  src = srcs.${stdenv.hostPlatform.system} or (throw "Unsupported system: ${stdenv.hostPlatform.system}");

in stdenv.mkDerivation {
  pname = "pi-coding-agent";
  inherit version;

  src = fetchurl {
    inherit (src) url sha256;
  };

  sourceRoot = "pi";

  # Bun standalone binaries have JS code appended after the ELF sections
  dontStrip = true;
  dontPatchELF = true;

  nativeBuildInputs = [ makeWrapper ]
    ++ lib.optionals stdenv.isLinux [ patchelf ];

  installPhase = ''
    runHook preInstall

    # Install the full pi directory structure (binary + supporting files)
    mkdir -p $out/lib/pi-coding-agent
    cp -r . $out/lib/pi-coding-agent/

    # Create bin wrapper that runs the binary from its lib directory
    # (pi expects supporting files like themes and wasm relative to itself)
    mkdir -p $out/bin
    makeWrapper $out/lib/pi-coding-agent/pi $out/bin/pi

    runHook postInstall
  '';

  # Manually patch the interpreter for bun standalone binaries on Linux
  postFixup = lib.optionalString stdenv.isLinux ''
    interpreter="${glibc}/lib/${if stdenv.hostPlatform.system == "aarch64-linux" then "ld-linux-aarch64.so.1" else "ld-linux-x86-64.so.2"}"
    patchelf --set-interpreter "$interpreter" $out/lib/pi-coding-agent/pi
  '';

  meta = with lib; {
    description = "Minimal terminal coding agent with extensible tools and session management";
    homepage = "https://github.com/badlogic/pi-mono/tree/main/packages/coding-agent";
    license = licenses.mit;
    maintainers = [ ];
    platforms = [ "aarch64-darwin" "x86_64-darwin" "x86_64-linux" "aarch64-linux" ];
    mainProgram = "pi";
  };
}
