#!/usr/bin/env bash
# Build qRemoteX standalone binary using PyInstaller.
#
# Usage:
#   ./scripts/build-binary.sh            # Build for current platform
#   ./scripts/build-binary.sh --clean    # Clean build (remove dist/build first)
#
# Output: dist/qremotex  (single executable, ~50MB)
#
# Prerequisites:
#   pip install pyinstaller
#   pip install -e ".[tools]"   # Install with tool extras

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

cd "$PROJECT_ROOT"

# Parse args
CLEAN=false
for arg in "$@"; do
    case "$arg" in
        --clean) CLEAN=true ;;
        *) echo "Unknown arg: $arg"; exit 1 ;;
    esac
done

# Clean previous builds
if [ "$CLEAN" = true ]; then
    echo "==> Cleaning previous builds..."
    rm -rf dist/ build/ __pycache__/
fi

# Check pyinstaller is available
if ! command -v pyinstaller &>/dev/null; then
    echo "ERROR: pyinstaller not found. Install with: pip install pyinstaller"
    exit 1
fi

echo "==> Building qRemoteX standalone binary..."
echo "    Platform: $(uname -s)-$(uname -m)"
echo "    Python:   $(python3 --version)"

pyinstaller qremotex.spec --noconfirm

BINARY="dist/qremotex"
if [ -f "$BINARY" ]; then
    SIZE=$(du -sh "$BINARY" | cut -f1)
    echo ""
    echo "==> Build successful!"
    echo "    Binary: $BINARY"
    echo "    Size:   $SIZE"
    echo ""
    echo "    Run with:"
    echo "      QRAPTOR_GATEWAY_URL=wss://gateway.example.com/ws \\"
    echo "      QRAPTOR_API_KEY=qrx_prod_... \\"
    echo "      ./dist/qremotex"
else
    echo "ERROR: Build failed — binary not found at $BINARY"
    exit 1
fi
