#!/bin/bash
# Build the frozen app for manual testing. On macOS this produces
# dist/Jarvis.app; on Linux dist/Jarvis/. There is no Inno-equivalent
# installer step on these platforms, so the bundle directory itself is
# the artefact you'd ship.

set -euo pipefail

cd "$(dirname "$0")/.."
PROJECT_ROOT="$(pwd)"

# Stamp a dev version file so jarvis.get_version() works in the bundle.
GIT_SHA="$(git rev-parse --short=7 HEAD 2>/dev/null || echo local)"
DEV_VERSION="dev-${GIT_SHA}"
echo "[build_installer] Stamping dev _version.py (${DEV_VERSION})..."
cat > "${PROJECT_ROOT}/src/jarvis/_version.py" <<EOF
# Auto-generated by scripts/build_installer.sh
VERSION = "${DEV_VERSION}"
RELEASE_CHANNEL = "develop"
EOF

echo "[build_installer] 🎨 Generating icons..."
python src/desktop_app/desktop_assets/generate_icons.py

echo "[build_installer] 🧹 Cleaning previous builds..."
rm -rf build dist

echo "[build_installer] 📦 Running PyInstaller..."
python -m PyInstaller jarvis_desktop.spec

if [[ "$OSTYPE" == "darwin"* ]]; then
    if [[ -d dist/Jarvis.app ]]; then
        echo
        echo "[build_installer] ✅ SUCCESS"
        echo "                  Bundle: ${PROJECT_ROOT}/dist/Jarvis.app"
        echo "[build_installer] ℹ️  No installer is produced on macOS."
    else
        echo "[build_installer] ❌ Bundle missing at dist/Jarvis.app" >&2
        exit 1
    fi
else
    if [[ -d dist/Jarvis ]]; then
        echo
        echo "[build_installer] ✅ SUCCESS"
        echo "                  Bundle: ${PROJECT_ROOT}/dist/Jarvis"
        echo "[build_installer] ℹ️  No installer is produced on Linux."
    else
        echo "[build_installer] ❌ Bundle missing at dist/Jarvis" >&2
        exit 1
    fi
fi
