with (import <nixpkgs> {});
with python312Packages;
let
  glibStorePath = lib.getLib glib;
  qtpyStorePath = lib.getLib qtpy;
  pyqt6StorePath = lib.getLib pyqt6;
  pyqt6SipStorePath = lib.getLib pyqt6-sip;
  qt6baseStorePath = lib.getLib qt6.qtbase;
  rapidfuzzStorePath = lib.getLib rapidfuzz;
  qdarkstyleStorePath = lib.getLib qdarkstyle;
in
stdenv.mkDerivation {
  name = "piker-qt6-poetry-shell";
  buildInputs = [
    # System requirements.
    glib
    qt6.qtbase
    libgcc.lib

    # Python requirements.
    python312Full
    poetry-core
    qdarkstyle
    rapidfuzz
    pyqt6
    qtpy
  ];
  src = null;
  shellHook = ''
    set -e

    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${libgcc.lib}/lib:${glibStorePath}/lib

    # Set the Qt plugin path
    # export QT_DEBUG_PLUGINS=1

    QTBASE_PATH="${qt6baseStorePath}"
    echo "qtbase path:    $QTBASE_PATH"
    echo ""
    export QT_PLUGIN_PATH="$QTBASE_PATH/lib/qt-6/plugins"
    export QT_QPA_PLATFORM_PLUGIN_PATH="$QT_PLUGIN_PATH/platforms"
    echo "qt plugin path: $QT_PLUGIN_PATH"
    echo ""

    # Maybe create venv & install deps
    poetry install --with uis

    # Use pyqt6 from System, patch activate script
    ACTIVATE_SCRIPT_PATH="$(poetry env info --path)/bin/activate"

    export RPDFUZZ_PATH="${rapidfuzzStorePath}/lib/python3.12/site-packages"
    export QDRKSTYLE_PATH="${qdarkstyleStorePath}/lib/python3.12/site-packages"
    export QTPY_PATH="${qtpyStorePath}/lib/python3.12/site-packages"
    export PYQT6_PATH="${pyqt6StorePath}/lib/python3.12/site-packages"
    export PYQT6_SIP_PATH="${pyqt6SipStorePath}/lib/python3.12/site-packages"
    echo "rapidfuzz at:   $RPDFUZZ_PATH"
    echo "qdarkstyle at:  $QDRKSTYLE_PATH"
    echo "qtpy at:        $QTPY_PATH" 
    echo "pyqt6 at:       $PYQT6_PATH"
    echo "pyqt6-sip at:   $PYQT6_SIP_PATH"
    echo ""

    PATCH="export PYTHONPATH=\""

    PATCH="$PATCH\$RPDFUZZ_PATH"
    PATCH="$PATCH:\$QDRKSTYLE_PATH"
    PATCH="$PATCH:\$QTPY_PATH"
    PATCH="$PATCH:\$PYQT6_PATH"
    PATCH="$PATCH:\$PYQT6_SIP_PATH"

    PATCH="$PATCH\""

    if grep -q "$PATCH" "$ACTIVATE_SCRIPT_PATH"; then
        echo "venv is already patched."
    else
        echo "patching $ACTIVATE_SCRIPT_PATH to use pyqt6 from nixos..."
        sed -i "\$i$PATCH" $ACTIVATE_SCRIPT_PATH
    fi

    poetry shell
  '';
}