#!/bin/bash

# StreamFlow Desktop App Build Script
# Builds AppImage for Linux

set -e

echo "========================================="
echo "StreamFlow Desktop AppImage Builder"
echo "========================================="
echo ""

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "❌ Node.js is not installed. Please install Node.js 18+ first."
    exit 1
fi

# Check if npm is installed
if ! command -v npm &> /dev/null; then
    echo "❌ npm is not installed. Please install npm first."
    exit 1
fi

echo "✓ Node.js version: $(node --version)"
echo "✓ npm version: $(npm --version)"
echo ""

# Check if we're in the correct directory
if [ ! -f "package.json" ]; then
    echo "❌ Error: package.json not found. Please run this script from the desktop-app directory."
    exit 1
fi

# Install dependencies if node_modules doesn't exist
if [ ! -d "node_modules" ]; then
    echo "📦 Installing dependencies..."
    npm install
    echo "✓ Dependencies installed"
    echo ""
else
    echo "✓ Dependencies already installed"
    echo ""
fi

# Create icon if it doesn't exist
if [ ! -f "build/icon.png" ]; then
    echo "⚠️  Warning: build/icon.png not found. Creating placeholder..."
    mkdir -p build
    
    # Create a simple PNG icon using ImageMagick if available
    if command -v convert &> /dev/null; then
        convert -size 512x512 xc:transparent -fill '#667eea' -draw "circle 256,256 256,50" -fill white -gravity center -pointsize 180 -annotate +0+0 "SF" build/icon.png
        echo "✓ Placeholder icon created"
    else
        echo "⚠️  ImageMagick not found. Please manually add an icon.png file to the build/ directory."
        echo "   Icon should be 512x512 PNG format."
    fi
    echo ""
fi

# Build the AppImage
echo "🔨 Building AppImage..."
echo ""

# Choose architecture
ARCH="${1:-x64}"
echo "Building for architecture: $ARCH"
echo ""

if [ "$ARCH" = "all" ]; then
    npm run build:linux
else
    npm run build:linux -- --$ARCH
fi

echo ""
echo "========================================="
echo "✅ Build Complete!"
echo "========================================="
echo ""

# List built files
if [ -d "dist" ]; then
    echo "Built files:"
    ls -lh dist/*.AppImage 2>/dev/null || echo "No AppImage files found in dist/"
    echo ""
    echo "AppImage location: $(pwd)/dist/"
else
    echo "⚠️  Warning: dist directory not found"
fi

echo ""
echo "To run the AppImage:"
echo "  chmod +x dist/StreamFlow-*.AppImage"
echo "  ./dist/StreamFlow-*.AppImage"
echo ""
