#!/bin/bash
# build-electron.sh
# Author: Matthew Raymer
# Description: Electron build script for TimeSafari application
# This script handles the complete Electron build process including cleanup,
# web build, Capacitor build, TypeScript compilation, and Electron packaging.
#
# Usage:
#   ./scripts/build-electron.sh                    # Development build (runs app)
#   ./scripts/build-electron.sh --dev              # Development build (runs app)
#   ./scripts/build-electron.sh --package          # Package build (creates distributable)
#   ./scripts/build-electron.sh --appimage         # Build AppImage package
#   ./scripts/build-electron.sh --deb              # Build Debian package
#   ./scripts/build-electron.sh --help             # Show help
#   ./scripts/build-electron.sh --verbose          # Enable verbose logging
#
# NPM Script Equivalents:
#   npm run build:electron                         # Development build
#   npm run build:electron:package                 # Package build
#   npm run build:electron:appimage                # AppImage package
#   npm run build:electron:deb                     # Debian package
#
# Exit Codes:
# 1 - Electron cleanup failed
# 2 - Web build failed
# 3 - Capacitor build failed
# 4 - TypeScript compilation failed
# 5 - Electron packaging failed
# 6 - Capacitor sync failed
# 7 - Asset generation failed
# 8 - Electron app launch failed

# Exit on any error
set -e

# Source common utilities
source "$(dirname "$0")/common.sh"

# Parse command line arguments
parse_args "$@"

# Print build header
print_header "TimeSafari Electron Build Process"
log_info "Starting Electron build process at $(date)"

# Setup environment for Electron build
setup_build_env "electron"

# Setup application directories
setup_app_directories

# Load environment from .env file if it exists
load_env_file ".env"

# Step 1: Clean Electron app
safe_execute "Cleaning Electron app" "npm run clean:electron || true" || exit 1

# Step 2: Clean dist directory
log_info "Cleaning dist directory..."
clean_build_artifacts "dist" "electron/app"

# Step 3: Build Capacitor version for Electron
safe_execute "Building Capacitor version" "npm run build:capacitor" || exit 2

# Step 4: Prepare Electron app directory
log_info "Preparing Electron app directory..."
mkdir -p electron/app

# Step 5: Copy built files to Electron
safe_execute "Copying web assets to Electron" "cp -r dist/* electron/app/" || exit 3

# Step 6: Validate and copy Capacitor configuration
safe_execute "Validating Capacitor configuration" "cp capacitor.config.json electron/capacitor.config.json" || exit 3

# Step 7: Navigate to electron directory and build TypeScript
safe_execute "Compiling TypeScript" "cd electron && npm run build && cd .." || exit 4

# Step 8: Sync with Capacitor (if needed)
safe_execute "Syncing with Capacitor" "npx cap sync electron || true" || exit 6

# Step 9: Generate assets (if available)
safe_execute "Generating assets" "npx capacitor-assets generate --electron || true" || exit 7

# Determine build action based on arguments
BUILD_ACTION="dev"
PACKAGE_TYPE=""

# Parse additional arguments for build type
for arg in "$@"; do
    case $arg in
        --package|--build)
            BUILD_ACTION="package"
            ;;
        --appimage)
            BUILD_ACTION="package"
            PACKAGE_TYPE="appimage"
            ;;
        --deb)
            BUILD_ACTION="package"
            PACKAGE_TYPE="deb"
            ;;
        --dev|--development)
            BUILD_ACTION="dev"
            ;;
        *)
            # Ignore unknown arguments
            ;;
    esac
done

# Execute build action
case $BUILD_ACTION in
    "package")
        if [ -n "$PACKAGE_TYPE" ]; then
            safe_execute "Building Electron package ($PACKAGE_TYPE)" "cd electron && ./build-packages.sh $PACKAGE_TYPE && cd .." || exit 5
        else
            safe_execute "Building Electron package" "cd electron && ./build-packages.sh && cd .." || exit 5
        fi
        ;;
    "dev")
        safe_execute "Starting Electron development app" "cd electron && npm run electron:start && cd .." || exit 8
        ;;
    *)
        log_error "Unknown build action: $BUILD_ACTION"
        exit 1
        ;;
esac

# Print build summary
case $BUILD_ACTION in
    "package")
        log_success "Electron package build completed successfully!"
        if [ -d "electron/dist" ]; then
            log_info "Package files available in: electron/dist/"
            ls -la electron/dist/ || true
        fi
        ;;
    "dev")
        log_success "Electron development build completed successfully!"
        log_info "Electron app should now be running"
        ;;
esac

print_footer "Electron Build"

# Exit with success
exit 0 