{
  lib,
  stdenv,
  fetchFromGitHub,
  nodejs,
  yarn,
  python3,
  poetry,
  makeWrapper,
  fetchYarnDeps,
  fixup-yarn-lock,
  ...
}:

stdenv.mkDerivation rec {
  pname = "tabby-web";
  version = "0.0.1";

  src = fetchFromGitHub {
    owner = "Eugeny";
    repo = "tabby-web";
    rev = "16847cea93f730814c1855241d8ebdea20b1ff6e";
    sha256 = "sha256-FaVJdizSQq600awY9HAwMNv6vpcjLVAVqdWnn+sYAxk=";
  };

  # Fetch yarn dependencies separately for reproducibility
  yarnDeps = fetchYarnDeps {
    yarnLock = "${src}/frontend/yarn.lock";
    hash = "sha256-NInsyKgp2+ppHJZLFn3qKW08rvSSIShhh2JbR91WgOk=";
  };

  nativeBuildInputs = [
    nodejs
    yarn
    python3
    poetry
    makeWrapper
    fixup-yarn-lock
  ];

  buildInputs = [
    python3
  ];

  propagatedBuildInputs = with python3.pkgs; [
    gunicorn
    django
  ];

  configurePhase = ''
    runHook preConfigure

    # Set up yarn
    export HOME=$TMPDIR
    cd frontend

    # Fix up yarn.lock and set up offline cache
    fixup-yarn-lock yarn.lock
    yarn config --offline set yarn-offline-mirror ${yarnDeps}
    yarn install --offline --frozen-lockfile --ignore-platform --ignore-scripts --no-progress --non-interactive
    patchShebangs node_modules/
    cd ..

    # Set up poetry
    export POETRY_CACHE_DIR=$TMPDIR/poetry-cache
    export POETRY_VENV_IN_PROJECT=1

    runHook postConfigure
  '';

  buildPhase = ''
    runHook preBuild

    echo "Building frontend..."
    cd frontend
    yarn run build
    cd ..

    echo "Backend is ready (dependencies will be handled by Nix)"

    runHook postBuild
  '';

  installPhase = ''
        runHook preInstall

        # Create output directories
        mkdir -p $out/lib/tabby-web
        mkdir -p $out/bin
        mkdir -p $out/share/tabby-web

        # Install backend
        cp -r backend/* $out/lib/tabby-web/
        
        # Install frontend build output
        if [ -d frontend/dist ]; then
          cp -r frontend/dist/* $out/share/tabby-web/
        elif [ -d frontend/build ]; then
          cp -r frontend/build/* $out/share/tabby-web/
        fi

        # Create main executable wrapper
        makeWrapper ${
          python3.withPackages (
            ps: with ps; [
              gunicorn
              django
            ]
          )
        }/bin/python $out/bin/tabby-web \
          --add-flags "-m gunicorn tabby_web.wsgi:application" \
          --set PYTHONPATH "$out/lib/tabby-web" \
          --set DJANGO_SETTINGS_MODULE "tabby_web.settings" \
          --set STATIC_ROOT "$out/share/tabby-web" \
          --run "cd $out/lib/tabby-web" \
          --run 'export DATABASE_URL="''${DATABASE_URL:-sqlite:///tmp/tabby-web.db}"' \
          --run 'export APP_DIST_STORAGE="''${APP_DIST_STORAGE:-file:///tmp/tabby-web-dist}"' \
          --run 'export PORT="''${PORT:-9000}"' \
          --add-flags '--bind "0.0.0.0:$PORT"' \
          --add-flags "--workers 4" \
          --add-flags "--timeout 120"

        # Create Django management wrapper
        makeWrapper ${
          python3.withPackages (ps: with ps; [ django ])
        }/bin/python $out/bin/tabby-web-manage \
          --add-flags "manage.py" \
          --set PYTHONPATH "$out/lib/tabby-web" \
          --set DJANGO_SETTINGS_MODULE "tabby_web.settings" \
          --set STATIC_ROOT "$out/share/tabby-web" \
          --run "cd $out/lib/tabby-web" \
          --run 'export DATABASE_URL="''${DATABASE_URL:-sqlite:///tmp/tabby-web.db}"' \
          --run 'export APP_DIST_STORAGE="''${APP_DIST_STORAGE:-file:///tmp/tabby-web-dist}"'

        # Create a help script
        cat > $out/bin/tabby-web-help << 'HELP_EOF'
    #!/bin/bash
    cat << 'HELP'
    Tabby Web - Terminal application server

    Usage: 
        tabby-web                    Start the server
        tabby-web-manage <command>   Run Django management commands
        tabby-web-help              Show this help

    Environment Variables:
        DATABASE_URL                 Database connection URL
                                    Examples: sqlite:///path/to/db.sqlite
                                             postgresql://user:pass@host:5432/dbname
        
        APP_DIST_STORAGE            Storage URL for app distributions
                                    Examples: file:///path/to/storage
                                             s3://bucket-name/path
                                             gcs://bucket-name/path
        
        PORT                        Server port (default: 9000)
        
        Social Authentication (optional):
        SOCIAL_AUTH_GITHUB_KEY      GitHub OAuth key
        SOCIAL_AUTH_GITHUB_SECRET   GitHub OAuth secret
        SOCIAL_AUTH_GITLAB_KEY      GitLab OAuth key
        SOCIAL_AUTH_GITLAB_SECRET   GitLab OAuth secret
        SOCIAL_AUTH_MICROSOFT_GRAPH_KEY      Microsoft Graph OAuth key
        SOCIAL_AUTH_MICROSOFT_GRAPH_SECRET   Microsoft Graph OAuth secret
        SOCIAL_AUTH_GOOGLE_OAUTH2_KEY        Google OAuth2 key
        SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET     Google OAuth2 secret

    Examples:
        # Development with defaults
        tabby-web
        
        # Production with PostgreSQL
        DATABASE_URL="postgresql://user:pass@localhost:5432/tabby" tabby-web
        
        # Run migrations
        tabby-web-manage migrate
        
        # Add app version
        tabby-web-manage add_version 1.0.156-nightly.2
    HELP
    HELP_EOF

        chmod +x $out/bin/tabby-web-help

        runHook postInstall
  '';

  meta = with lib; {
    description = "Web-based terminal application";
    homepage = "https://github.com/Eugeny/tabby-web";
    license = licenses.mit;
    maintainers = [ ];
    platforms = platforms.linux ++ platforms.darwin;
  };
}
