{ pkgs, lib, ... }:

let
  genv = pkgs.writeShellScriptBin "genv" ''
    #!/usr/bin/env bash
    set -e

    DISTRO="$1"
    PRESET="$2"

    if [ -z "$DISTRO" ] || [ -z "$PRESET" ]; then
      echo "Usage: genv <distro> <preset>"
      exit 1
    fi

    PROJECT=$(basename "$PWD")
    BOX="genv-$PROJECT"

    # distro mapping
    case "$DISTRO" in
      ubuntu) IMAGE="docker.io/library/ubuntu:24.04" ;;
      arch) IMAGE="docker.io/library/archlinux:latest" ;;
      alpine) IMAGE="docker.io/library/alpine:latest" ;;
      *) IMAGE="$DISTRO" ;;
    esac

    echo "[genv] image: $IMAGE"

    # container nur erstellen wenn nötig
    if ! distrobox list | grep -q "$BOX"; then
      distrobox create --name "$BOX" --image "$IMAGE"
    fi

    mkdir -p .genv

    # preset kopieren
    cp ${./presets}/$PRESET.sh .genv/setup.sh
    chmod +x .genv/setup.sh

    # envrc generieren
    cat > .envrc <<EOF
export GENV_BOX="$BOX"

# container starten
distrobox start "$GENV_BOX" >/dev/null 2>&1 || true

# setup einmalig
if [ ! -f .genv/.init ]; then
  echo "[genv] setup läuft"
  distrobox enter "$GENV_BOX" -- bash .genv/setup.sh
  touch .genv/.init
fi

# tmux workflow
if [ -z "$TMUX" ]; then
  tmux new-session -A -s "$GENV_BOX" \
    \; new-window -n editor "nvim" \
    \; new-window -n dev "distrobox enter $GENV_BOX"
fi
EOF

    echo "[genv] fertig → direnv allow"
  '';
in
{
  home.packages = [ genv ];
}
