#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "$0")/.."

export PYINSTALLER_CONFIG_DIR="${PYINSTALLER_CONFIG_DIR:-$PWD/.pyinstaller}"
mkdir -p "${PYINSTALLER_CONFIG_DIR}"

if [ ! -d ".venv" ]; then
  python3 -m venv .venv
fi

# shellcheck disable=SC1091
source .venv/bin/activate

if [ -z "${EKSAMENAPP_APP_VERSION:-}" ] && [ -f "VERSION" ]; then
  EKSAMENAPP_APP_VERSION="$(tr -d '[:space:]' < VERSION)"
  export EKSAMENAPP_APP_VERSION
fi

if [ "${SKIP_PIP_INSTALL:-0}" != "1" ]; then
  if [ "${UPGRADE_PIP:-0}" = "1" ]; then
    python -m pip install --upgrade pip
  fi
  python -m pip install -r requirements.txt
  if [ "${INCLUDE_OPTIONAL_DEPS:-1}" = "1" ]; then
    python -m pip install -r requirements-optional.txt
  else
    echo "Skipping requirements-optional.txt (set INCLUDE_OPTIONAL_DEPS=1 to include)."
  fi
  python -m pip install -r requirements-packaging.txt
else
  echo "Skipping pip install (SKIP_PIP_INSTALL=1)."
fi

if ! command -v pyinstaller >/dev/null 2>&1; then
  echo "pyinstaller not found in .venv. Install dependencies or unset SKIP_PIP_INSTALL."
  exit 1
fi

APP_STAGE_DIR="packaging/pyinstaller/app"
rm -rf "${APP_STAGE_DIR}"
mkdir -p "${APP_STAGE_DIR}"

ITEMS=(
  "VERSION"
  "Main.py"
  "ask.py"
  "build_index.py"
  "chunk_note.py"
  "fetch_text_from_selected_onenote_url.py"
  "llm_provider.py"
  "requirements.txt"
  "requirements-optional.txt"
  ".env.example"
  "DEPLOYMENT.md"
  "PACKAGING_ROADMAP.md"
  "scripts"
  "server"
)

for item in "${ITEMS[@]}"; do
  if [ -e "${item}" ]; then
    cp -R "${item}" "${APP_STAGE_DIR}/"
  else
    echo "[WARN] Missing item (skipped): ${item}"
  fi
done

rm -rf "${APP_STAGE_DIR}/server/data"
find "${APP_STAGE_DIR}" -type d -name "__pycache__" -prune -exec rm -rf {} +
find "${APP_STAGE_DIR}" -type f \( -name "*.pyc" -o -name "*.pyo" -o -name ".DS_Store" \) -delete

pyinstaller --noconfirm --clean packaging/pyinstaller/eksamenapp.spec

echo "Desktop bundle ready: dist/ATHENODE-desktop"
