#!/bin/bash
# Build Windows executables using PyInstaller via Wine
set -e
cd "$(cd "$(dirname "$0")" && pwd)"

WINEPYTHON="python-win/python.exe"
DIST_DIR="./dist"
BUILD_DIR="./build"

echo "Building Windows executables via Wine Python + PyInstaller..."

# Verify Wine Python works
if ! wine "$WINEPYTHON" --version 2>/dev/null; then
    echo "Wine Python not found or not working: $WINEPYTHON"
    exit 1
fi

# Ensure PyInstaller is available
wine "$WINEPYTHON" -c "import PyInstaller" 2>/dev/null || {
    echo "PyInstaller not found, installing..."
    wine "$WINEPYTHON" -m pip install pyinstaller 2>&1 | tail -3
}

# Build agent (console)
echo "Building hermes-node-agent.exe..."
rm -rf "$DIST_DIR/hermes-node-agent.exe" "$BUILD_DIR"
wine "$WINEPYTHON" -m PyInstaller \
  --onefile \
  --name hermes-node-agent \
  --distpath "$DIST_DIR" \
  --workpath "$BUILD_DIR/agent" \
  --specpath . \
  --console \
  --noconfirm \
  hermes_node_agent.py 2>&1 | tail -10

# Build GUI manager
echo "Building hermes-node-manager.exe..."
wine "$WINEPYTHON" -m PyInstaller \
  --onefile \
  --windowed \
  --name hermes-node-manager \
  --distpath "$DIST_DIR" \
  --workpath "$BUILD_DIR/manager" \
  --specpath . \
  --noconfirm \
  agent-manager.py 2>&1 | tail -10

# Verify
if [ -f "$DIST_DIR/hermes-node-agent.exe" ]; then
    SIZE=$(ls -lh "$DIST_DIR/hermes-node-agent.exe" | awk '{print $5}')
    echo "hermes-node-agent.exe built: $SIZE"
    file "$DIST_DIR/hermes-node-agent.exe" | grep -q "PE32" && echo "Verified: PE32+ executable"
else
    echo "Build failed"
    exit 1
fi

if [ -f "$DIST_DIR/hermes-node-manager.exe" ]; then
    SIZE=$(ls -lh "$DIST_DIR/hermes-node-manager.exe" | awk '{print $5}')
    echo "hermes-node-manager.exe built: $SIZE"
fi

echo "Done. Exes in: ./$DIST_DIR/"
