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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PYTHON_BOOTSTRAP="${OWALISAATTORI_PYTHON:-python3}"
BUILD_VENV_DIR="${ROOT_DIR}/.venv-python-api-build"
API_SCRIPT="${ROOT_DIR}/scripts/owalisaattori_api.py"
OUT_DIR="${ROOT_DIR}/scripts/bin"
BUILD_ROOT="${ROOT_DIR}/.build/pyinstaller"
WORK_DIR="${BUILD_ROOT}/work"
SPEC_DIR="${BUILD_ROOT}/spec"
NAME="owalisaattori_api"
BINARY_PATH="${OUT_DIR}/${NAME}"

if [[ ! -f "${API_SCRIPT}" ]]; then
  echo "Virhe: API-skripti puuttuu: ${API_SCRIPT}"
  exit 1
fi

if ! command -v "${PYTHON_BOOTSTRAP}" >/dev/null 2>&1; then
  echo "Virhe: Pythonia ei löydy komennolla ${PYTHON_BOOTSTRAP}"
  exit 1
fi

if [[ ! -x "${BUILD_VENV_DIR}/bin/python3" ]]; then
  echo "==> Luodaan build-venv: ${BUILD_VENV_DIR}"
  "${PYTHON_BOOTSTRAP}" -m venv "${BUILD_VENV_DIR}"
fi

PYTHON_BIN="${BUILD_VENV_DIR}/bin/python3"

if ! "${PYTHON_BIN}" - <<'PY' >/dev/null 2>&1
import importlib.util, sys
mods = ["PyInstaller", "docx", "certifi"]
missing = [m for m in mods if importlib.util.find_spec(m) is None]
if missing:
    print(",".join(missing))
    sys.exit(1)
PY
then
  echo "==> Asennetaan build-riippuvuudet venviin"
  "${PYTHON_BIN}" -m pip install -r "${ROOT_DIR}/scripts/requirements-build.txt"
fi

mkdir -p "${OUT_DIR}" "${WORK_DIR}" "${SPEC_DIR}"
rm -f "${BINARY_PATH}"

"${PYTHON_BIN}" -m PyInstaller \
  --noconfirm \
  --clean \
  --onefile \
  --name "${NAME}" \
  --distpath "${OUT_DIR}" \
  --workpath "${WORK_DIR}" \
  --specpath "${SPEC_DIR}" \
  --collect-all docx \
  --collect-all certifi \
  "${API_SCRIPT}"

chmod +x "${BINARY_PATH}"

echo "Python API bundle valmis: ${BINARY_PATH}"
file "${BINARY_PATH}" || true
