#!/bin/bash
# Build script for Unix systems (Linux/macOS)

echo "🚀 MbetterClient Build Script"
echo "============================="

USE_BUILT_PYQT6=false

# Check if Python 3 is available
if ! command -v python3 &> /dev/null; then
    echo "❌ Python 3 is required but not installed."
    exit 1
fi

# Check if built PyQt6 directory exists
if [ -d "pyqt6_built" ]; then
    echo "📦 Built PyQt6 found in pyqt6_built/. Using local build..."
    USE_BUILT_PYQT6=true
else
    USE_BUILT_PYQT6=false
fi

# Check if virtual environment exists
if [ ! -d "venv" ]; then
    echo "⚠️  Virtual environment not found. Creating one..."
    python3 -m venv venv
fi

# Activate virtual environment
echo "🔧 Activating virtual environment..."
source venv/bin/activate

# Set paths for built PyQt6 if available
if $USE_BUILT_PYQT6; then
    export PYTHONPATH="pyqt6_built/usr/lib/python3/dist-packages:$PYTHONPATH"
    export LD_LIBRARY_PATH="pyqt6_built/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH"
fi

# Install/upgrade dependencies
echo "📦 Installing dependencies..."
if [ -n "$VIRTUAL_ENV" ]; then
    echo "   📦 Using virtual environment: $VIRTUAL_ENV"
    pip install --upgrade pip
    if $USE_BUILT_PYQT6; then
        pip install -r requirements.txt --ignore-installed PyQt6 PyQt6-WebEngine
    else
        pip install -r requirements.txt
    fi

    # Verify critical package installations
    echo "   🔍 Verifying critical package installations..."

    # Check ffmpeg-python
    python3 -c "import ffmpeg; print('✅ ffmpeg-python installed successfully')" || {
        echo "   ❌ ffmpeg-python import failed, installing..."
        pip install ffmpeg-python>=0.2.0
    }

    # Check dbus (optional, for Qt D-Bus support)
    python3 -c "import dbus; print('✅ dbus installed successfully')" || {
        echo "   ⚠️  dbus not available, trying to install..."
        pip install dbus-python || {
            echo "   ❌ Could not install dbus-python, Qt D-Bus support will be limited"
        }
    }
else
    echo "   ⚠️  Not in virtual environment, using --break-system-packages"
    pip install --upgrade pip --break-system-packages
    pip install -r requirements.txt --break-system-packages
fi

# Backup MBetterDiscovery.exe if it exists
if [ -f "dist/MBetterDiscovery.exe" ]; then
    echo "📦 Backing up MBetterDiscovery.exe..."
    cp dist/MBetterDiscovery.exe /tmp/MBetterDiscovery.exe.backup
fi

# Run the build script
echo "🔨 Starting build process..."
python3 build.py

# Check if build was successful and create zip package
if [ -d "dist" ] && [ "$(ls -A dist)" ]; then
    echo "📦 Build successful, creating latest zip package..."

    # Find the main executable (should be MbetterClient on Unix systems)
    EXECUTABLE_NAME="MbetterClient"
    if [ -f "dist/$EXECUTABLE_NAME" ]; then
        echo "   📁 Found executable: $EXECUTABLE_NAME"

        # Create zip file
        cd dist
        zip -r mbetterc_latest.zip "$EXECUTABLE_NAME"
        echo "   📦 Created: mbetterc_latest.zip"

        # Generate MD5 checksums for both binary and zip
        if command -v md5sum &> /dev/null; then
            # Calculate MD5 for the binary
            BINARY_MD5=$(md5sum "$EXECUTABLE_NAME" | cut -d' ' -f1)
            # Calculate MD5 for the zip
            ZIP_MD5=$(md5sum mbetterc_latest.zip | cut -d' ' -f1)

            # Write both checksums to file
            echo "client:$BINARY_MD5" > mbetter_latest.md5.txt
            echo "zip:$ZIP_MD5" >> mbetter_latest.md5.txt

            echo "   🔐 Generated MD5 checksums: mbetter_latest.md5.txt"
            echo "      Binary MD5: $BINARY_MD5"
            echo "      Zip MD5: $ZIP_MD5"
        else
            echo "   ⚠️  md5sum command not available, skipping checksum generation"
        fi

        cd ..
    else
        echo "   ⚠️  Executable $EXECUTABLE_NAME not found in dist directory"
    fi
else
    echo "❌ Build failed or dist directory is empty"
    exit 1
fi

# Restore MBetterDiscovery.exe if backup exists
if [ -f "/tmp/MBetterDiscovery.exe.backup" ]; then
    echo "📦 Restoring MBetterDiscovery.exe..."
    mkdir -p dist
    cp /tmp/MBetterDiscovery.exe.backup dist/MBetterDiscovery.exe
    rm /tmp/MBetterDiscovery.exe.backup
fi

# Removed Qt platform plugins and qt.conf copying for self-contained binary
echo "📦 Building self-contained binary - no external Qt files needed"

echo "✅ Build script completed!"