#!/bin/zsh
set -e # Exit on any error

log() {
    echo "🔨 $1"
}

error() {
    echo "❌ $1"
    exit 1
}

# Build Relay component
log "Building Relay..."
(cd ../Relay && ./build.sh) || error "Relay build failed"

# Setup extras directory
log "Setting up extras directory..."
mkdir -p extras/linux extras/macos
cp ../Relay/dist/relay-x86_64-unknown-linux-gnu ./extras/linux/relay || error "Failed to copy Linux relay"
cp ../Relay/dist/relay-x86_64-apple-darwin ./extras/macos/relay || error "Failed to copy macOS relay"

# Clean previous builds
log "Cleaning previous builds..."
sudo rm -rf dist
sudo rm -rf out

# Build Linux version
log "Building Linux version..."
bun run build:linux || error "Linux build failed"
npm install || error "npm install failed"

# Build macOS version using Docker
log "Building macOS version..."
docker run --rm -it \
    -v "${PWD}:/project" \
    -v "${HOME}/.ssh:/root/.ssh" \
    -v /var/run/docker.sock:/var/run/docker.sock \
    electronuserland/builder \
    /bin/bash -c "npm install --ignore-scripts && npm run build:mac" || error "macOS build failed"

# Output paths
VERSION=$(node -p "require('./package.json').version")
log "Build complete! 🎉"
echo "📦 Build artifacts:"
echo "🐧 Linux AppImage: ./dist/Eve-${VERSION}.AppImage"
echo "🐧 Linux Flatpak: ./dist/Eve-${VERSION}-x86_64.flatpak"
echo "🍎 macOS ZIP: ./dist/Eve-${VERSION}-mac.zip"

log "Generating SHA256 hashes..."
echo "🔐 SHA256 Hashes:"
pushd dist
for file in "Eve-${VERSION}.AppImage" "Eve-${VERSION}-x86_64.flatpak" "Eve-${VERSION}-mac.zip"; do
    if [ -f "$file" ]; then
        shasum -a 256 "$file" | tee "$file.sha256"
        echo "✅ Generated hash for $file"
    else
        echo "⚠️  Missing artifact: $file"
    fi
done

log "Generating SHA512 hashes..."
echo "🔐 SHA512 Hashes:"
for file in "Eve-${VERSION}.AppImage" "Eve-${VERSION}-x86_64.flatpak" "Eve-${VERSION}-mac.zip"; do
    if [ -f "$file" ]; then
        shasum -a 512 "$file" | tee "$file.sha512"
        echo "✅ Generated hash for $file"
    else
        echo "⚠️  Missing artifact: $file"
    fi
done

popd
