#!/usr/bin/env bash
# Build the Windows Electron output via electron-builder.
# Produces an unpacked directory at packages/frontend/release/win-unpacked.
#
# Usage:
#   bin/build-pkg-windows
#
# Override the API URL the frontend bundle points to:
#   VITE_API_URL="http://your-host:18390" bin/build-pkg-windows

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
FRONTEND_DIR="$PROJECT_DIR/packages/frontend"
VITE_API_URL="${VITE_API_URL:-http://localhost:18390}"

cd "$PROJECT_DIR"

# Install deps (electron + electron-builder live as frontend devDependencies)
bun install

# Build the SPA bundle, then package it for Windows (unpacked dir)
cd "$FRONTEND_DIR"
VITE_API_URL="$VITE_API_URL" bun run dist:win

WIN_BUILD="$FRONTEND_DIR/release/win-unpacked"

if [ ! -d "$WIN_BUILD" ]; then
	echo "Build failed: no win-unpacked directory found at $WIN_BUILD" >&2
	exit 1
fi

echo ""
echo "Windows Electron build ready at:"
echo "  $WIN_BUILD"
echo ""
echo "Copy that folder to a Windows machine and run Dispatch.exe."
