{ lib
, stdenv
, python3
, fetchFromGitHub
, rustPlatform
, SDL2
, libiconv
, darwin
}:

python3.pkgs.buildPythonApplication rec {
  pname = "pyxel";
  version = "2.0.13";
  pyproject = true;

  disabled = python3.pythonOlder "3.7";

  src = fetchFromGitHub {
    owner = "kitao";
    repo = "pyxel";
    rev = "v${version}";
    hash = "sha256-0pVeIYDt8sz3eIQU/mU443fVWYjhShTpFKoPpM/PFf0=";
  };

  patches = [ ./never-bundle-sdl2.patch ];

  postPatch = ''
    cp ${./Cargo.lock} rust/Cargo.lock
  '';

  cargoRoot = "rust";

  cargoDeps = rustPlatform.importCargoLock {
    # generated by running `cargo generate-lockfile` in the `rust` directory
    lockFile = ./Cargo.lock;
  };

  buildAndTestSubdir = "python";

  nativeBuildInputs = with rustPlatform; [
    cargoSetupHook
    maturinBuildHook
    bindgenHook
  ];

  buildInputs = [ SDL2 ] ++ lib.optionals stdenv.isDarwin [
    libiconv
    darwin.apple_sdk.frameworks.IOKit
  ];

  env.NIX_CFLAGS_COMPILE = "-I${lib.getDev SDL2}/include/SDL2";

  # Tests want to use the display
  doCheck = false;

  pythonImportsCheck = [
    "pyxel"
    "pyxel.pyxel_wrapper"
  ];

  meta = {
    changelog = "https://github.com/kitao/pyxel/tree/${src.rev}/CHANGELOG.md";
    description = "Retro game engine for Python";
    homepage = "https://github.com/kitao/pyxel";
    license = lib.licenses.mit;
    mainProgram = "pyxel";
    maintainers = with lib.maintainers; [ tomasajt ];
    platforms = lib.platforms.linux ++ lib.platforms.darwin;
  };
}
