#!/bin/bash
# Copyright 2026, Jiri Eischmann <jiri@eischmann.cz> and the meshy contributors
# SPDX-License-Identifier: GPL-3.0-or-later

# Create fully self-contained Meshy.app bundle
# Bundles Python, GTK4, libadwaita, and all dependencies
# Result: Users can drag-and-drop to Applications with no runtime dependencies
#
# NOTE: Apple notarization currently fails for standalone bundles due to
# Python.framework signing complexity. The bundle can be signed but not notarized.
# For notarized distribution, use build-homebrew-bundle.sh instead.

set -e

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

info() { echo -e "${GREEN}==>${NC} $1"; }
warn() { echo -e "${YELLOW}Warning:${NC} $1"; }
error() { echo -e "${RED}Error:${NC} $1"; exit 1; }

[[ "$(uname)" == "Darwin" ]] || error "Must run on macOS"

# Parse command line options
SIGN_IDENTITY=""
CREATE_DMG=false

while [[ $# -gt 0 ]]; do
    case "$1" in
        --sign)
            SIGN_IDENTITY="$2"
            shift 2
            ;;
        --dmg)
            CREATE_DMG=true
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --sign IDENTITY    Sign the bundle with specified identity"
            echo "                     (default: unsigned)"
            echo "  --dmg              Create DMG installer after building"
            echo "  --help, -h         Show this help message"
            echo ""
            echo "Examples:"
            echo "  $0                              # Build unsigned bundle"
            echo "  $0 --dmg                        # Build and create unsigned DMG"
            echo "  $0 --sign \"Developer ID\"       # Build and sign"
            echo "  $0 --sign \"Developer ID\" --dmg  # Build, sign, and create DMG"
            exit 0
            ;;
        *)
            error "Unknown option: $1 (use --help for usage)"
            ;;
    esac
done

# Get version using same logic as meson.build (matching Linux versioning)
# If on a tag, use tag; otherwise use date version (YY.MM.DD format)
if git describe --tags --exact-match >/dev/null 2>&1; then
    # On a tag - use tag version (e.g., 26.06)
    VERSION=$(git describe --tags --exact-match 2>/dev/null)
else
    # Not on a tag - use date version matching meson's date_version (YY.MM.DD)
    VERSION=$(python3 -c 'import time; print(time.strftime("%y.%m.%d", time.gmtime()))')
fi

# Configuration
APP_NAME="Meshy"
APP_DIR="dist/${APP_NAME}.app"
CONTENTS_DIR="$APP_DIR/Contents"
MACOS_DIR="$CONTENTS_DIR/MacOS"
RESOURCES_DIR="$CONTENTS_DIR/Resources"
FRAMEWORKS_DIR="$CONTENTS_DIR/Frameworks"

info "Building self-contained ${APP_NAME}.app bundle (version ${VERSION})"

# Step 1: Build base app
info "Step 1/7: Building base application"
bash build-aux/macos/build-app-bundle.sh

# Step 2: Create Python virtual environment in bundle
info "Step 2/7: Creating bundled Python environment"
mkdir -p "$FRAMEWORKS_DIR"

# Copy Python framework from Homebrew
PYTHON_FW_SRC="/opt/homebrew/opt/python@3.14/Frameworks/Python.framework"
PYTHON_FW_DEST="$FRAMEWORKS_DIR/Python.framework"

if [[ ! -d "$PYTHON_FW_SRC" ]]; then
    error "Python framework not found at $PYTHON_FW_SRC"
fi

info "Copying Python.framework (this takes a moment...)"
cp -RL "$PYTHON_FW_SRC" "$PYTHON_FW_DEST"

# Make Python framework writable for modifications
chmod -R u+w "$PYTHON_FW_DEST"

# Step 3: Install Python dependencies into bundle
info "Step 3/7: Installing Python packages"
BUNDLE_PYTHON="$PYTHON_FW_DEST/Versions/3.14/bin/python3.14"

# Force ARM64 architecture to avoid Rosetta requirement
export ARCHFLAGS="-arch arm64"
export _PYTHON_HOST_PLATFORM="macosx-14.0-arm64"
arch -arm64 "$BUNDLE_PYTHON" -m pip install \
    --target="$RESOURCES_DIR/lib/python-packages" \
    pycryptodome \
    pyserial \
    segno \
    pyobjc-framework-Cocoa \
    pyobjc-framework-CoreBluetooth \
    pyobjc-framework-CoreLocation \
    pyobjc-framework-AVFoundation \
    pyobjc-framework-Vision \
    pyobjc-framework-UserNotifications \
    pyobjc-framework-libdispatch \
    pygobject

# Strip x86_64 architecture from universal binaries to avoid Rosetta requirement
info "Stripping x86_64 from universal binaries..."
find "$RESOURCES_DIR/lib/python-packages" -type f \( -name "*.so" -o -name "*.dylib" \) | while read -r binary; do
    if file "$binary" | grep -q "universal binary"; then
        lipo "$binary" -thin arm64 -output "$binary.arm64" 2>/dev/null && mv "$binary.arm64" "$binary" || true
    fi
done

# Step 4: Bundle GTK4 and dependencies
info "Step 4/7: Bundling GTK4 frameworks and libraries"

# Function to copy library and its dependencies
copy_lib_with_deps() {
    local lib=$1
    local src="/opt/homebrew/lib/$lib"
    local dest="$FRAMEWORKS_DIR/$lib"

    if [[ -f "$src" && ! -f "$dest" ]]; then
        cp "$src" "$dest"
        chmod u+w "$dest"
    fi
}

# Core GTK4 libraries and ALL their dependencies
LIBS=(
    # GTK/Adwaita
    "libgtk-4.1.dylib"
    "libadwaita-1.0.dylib"
    "libadwaita-1.1.dylib"
    "libadwaita-1.dylib"
    # GLib family
    "libglib-2.0.0.dylib"
    "libgobject-2.0.0.dylib"
    "libgio-2.0.0.dylib"
    "libgmodule-2.0.0.dylib"
    "libgthread-2.0.0.dylib"
    "libgirepository-2.0.0.dylib"
    # Graphics
    "libgdk_pixbuf-2.0.0.dylib"
    "libcairo.2.dylib"
    "libcairo-gobject.2.dylib"
    "libcairo-script-interpreter.2.dylib"
    "libpixman-1.0.dylib"
    # Text rendering
    "libpango-1.0.0.dylib"
    "libpangocairo-1.0.0.dylib"
    "libpangoft2-1.0.0.dylib"
    "libharfbuzz.0.dylib"
    "libharfbuzz-gobject.0.dylib"
    "libharfbuzz-subset.0.dylib"
    "libfribidi.0.dylib"
    "libthai.0.dylib"
    "libgraphite2.3.dylib"
    # Graphics libraries
    "libgraphene-1.0.0.dylib"
    "libepoxy.0.dylib"
    # Core libraries
    "libffi.8.dylib"
    "libintl.8.dylib"
    "libpcre2-8.0.dylib"
    "libpng16.16.dylib"
    "libfreetype.6.dylib"
    "libfontconfig.1.dylib"
    "libjpeg.8.dylib"
    "libtiff.6.dylib"
    # Map
    "libshumate-1.0.1.dylib"
    "libjson-glib-1.0.0.dylib"
    "libsoup-3.0.0.dylib"
    # XML/Data
    "libxml2.2.dylib"
    "libxmlb.2.dylib"
    "libfyaml.0.dylib"
    "libsqlite3.0.dylib"
    "libsqlite3.dylib"
    # Compression
    "liblzma.5.dylib"
    "libbz2.1.0.dylib"
    "libz.1.dylib"
    "libzstd.1.dylib"
    # Security/Crypto
    "libssl.3.dylib"
    "libcrypto.3.dylib"
    # Other
    "libiconv.2.dylib"
    "libgstreamer-1.0.0.dylib"
    "libgstbase-1.0.0.dylib"
    "libprotobuf-c.1.dylib"
    "libpsl.5.dylib"
    "libnghttp2.14.dylib"
    # X11 (needed by Cairo on some systems)
    "libX11.6.dylib"
    "libXext.6.dylib"
    "libXrender.1.dylib"
    "libxcb.1.dylib"
    "libxcb-render.0.dylib"
    "libxcb-shm.0.dylib"
    "libXau.6.dylib"
    "libXdmcp.6.dylib"
    # Additional dependencies
    "libappstream.5.dylib"
    "libdatrie.1.dylib"
    "libidn2.0.dylib"
    "libunistring.5.dylib"
    "liblzo2.2.dylib"
)

for lib in "${LIBS[@]}"; do
    copy_lib_with_deps "$lib"
done

# Special case: SQLite (used by Python)
# Copy the versioned library and create symlinks
SQLITE_SRC="/opt/homebrew/opt/sqlite/lib/libsqlite3.3.53.1.dylib"
SQLITE_DEST="$FRAMEWORKS_DIR/libsqlite3.3.53.1.dylib"
if [[ -f "$SQLITE_SRC" && ! -f "$SQLITE_DEST" ]]; then
    cp "$SQLITE_SRC" "$SQLITE_DEST"
    chmod u+w "$SQLITE_DEST"
    # Create symlinks
    ln -sf libsqlite3.3.53.1.dylib "$FRAMEWORKS_DIR/libsqlite3.dylib"
    ln -sf libsqlite3.3.53.1.dylib "$FRAMEWORKS_DIR/libsqlite3.0.dylib"
fi

# Bundle GObject Introspection typelibs
info "Bundling GObject typelibs"
TYPELIB_DEST="$RESOURCES_DIR/lib/girepository-1.0"
mkdir -p "$TYPELIB_DEST"

# Follow symlinks to copy actual typelib files (not broken symlinks)
find /opt/homebrew/lib/girepository-1.0 -name "*.typelib" -type l -exec sh -c 'cp -L "$1" "'$TYPELIB_DEST'/$(basename "$1")"' _ {} \;

# Bundle GTK modules and data
info "Bundling GTK modules and themes"
mkdir -p "$RESOURCES_DIR/lib/gtk-4.0/4.0.0"
cp -RL "/opt/homebrew/lib/gtk-4.0/4.0.0"/* "$RESOURCES_DIR/lib/gtk-4.0/4.0.0/" 2>/dev/null || true
# Also copy any top-level gtk-4.0 files
cp -RL "/opt/homebrew/lib/gtk-4.0"/*.* "$RESOURCES_DIR/lib/gtk-4.0/" 2>/dev/null || true

# Bundle GDK-Pixbuf loaders (follow symlinks with -L)
mkdir -p "$RESOURCES_DIR/lib/gdk-pixbuf-2.0"
cp -RL "/opt/homebrew/lib/gdk-pixbuf-2.0" "$RESOURCES_DIR/lib/" 2>/dev/null || true

# Fix loaders.cache to point to bundled loaders instead of Homebrew
LOADERS_CACHE="$RESOURCES_DIR/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache"
if [[ -f "$LOADERS_CACHE" ]]; then
    sed -i '' 's|/opt/homebrew/lib/gdk-pixbuf-2.0/2.10.0/loaders|@executable_path/../Resources/lib/gdk-pixbuf-2.0/2.10.0/loaders|g' "$LOADERS_CACHE"
    sed -i '' 's|/opt/homebrew/Cellar/[^/]*/lib/gdk-pixbuf-2.0/2.10.0/loaders|@executable_path/../Resources/lib/gdk-pixbuf-2.0/2.10.0/loaders|g' "$LOADERS_CACHE"
fi

# Bundle themes and icons
info "Bundling icon themes (Adwaita + hicolor)"
mkdir -p "$RESOURCES_DIR/share"
cp -RL "/opt/homebrew/share/icons" "$RESOURCES_DIR/share/" 2>/dev/null || true
cp -RL "/opt/homebrew/share/themes" "$RESOURCES_DIR/share/" 2>/dev/null || true

# Update icon caches for bundled themes
if command -v gtk4-update-icon-cache >/dev/null 2>&1; then
    for icon_theme in "$RESOURCES_DIR/share/icons"/*; do
        if [[ -d "$icon_theme" && -f "$icon_theme/index.theme" ]]; then
            theme_name=$(basename "$icon_theme")
            gtk4-update-icon-cache -f -t "$icon_theme" 2>/dev/null || warn "Could not update icon cache for $theme_name"
        fi
    done
fi

# Copy GResource file (compiled UI resources)
cp "builddir-macos/data/meshy.gresource" "$RESOURCES_DIR/share/" 2>/dev/null || \
cp "data/page.codeberg.sesivany.Meshy.gresource" "$RESOURCES_DIR/share/meshy.gresource" 2>/dev/null || \
warn "Could not find GResource file"

# Step 5: Fix library paths with install_name_tool
info "Step 5/7: Fixing library paths"

fix_library_paths() {
    local target=$1

    if [[ ! -f "$target" ]]; then
        return
    fi

    # Change ID if it's a dylib
    if [[ "$target" == *.dylib ]]; then
        local filename=$(basename "$target")
        install_name_tool -id "@executable_path/../Frameworks/$filename" "$target" 2>/dev/null || true
    fi

    # Get all dependencies (including Cellar paths)
    local deps=$(otool -L "$target" 2>/dev/null | grep -E '^\s+/(opt/homebrew|usr/local)' | awk '{print $1}')

    for dep in $deps; do
        local depname=$(basename "$dep")

        # Fix Python.framework references
        if [[ "$dep" == */Python.framework/Versions/*/Python ]]; then
            # Use @loader_path for files inside Python.framework, @executable_path for others
            if [[ "$target" == *"/Python.framework/"* ]]; then
                install_name_tool -change "$dep" "@loader_path/../Python" "$target" 2>/dev/null || true
            else
                install_name_tool -change "$dep" "@executable_path/../Frameworks/Python.framework/Versions/3.14/Python" "$target" 2>/dev/null || true
            fi
        # Fix regular dylib references
        elif [[ -f "$FRAMEWORKS_DIR/$depname" ]]; then
            install_name_tool -change "$dep" "@executable_path/../Frameworks/$depname" "$target" 2>/dev/null || true
        fi
    done

    # Re-sign with ad-hoc signature after modification
    codesign --force --sign - "$target" 2>/dev/null || true
}

# Fix Python framework
info "Fixing Python framework paths"

# Fix Python.framework library ID first
PYTHON_LIB="$PYTHON_FW_DEST/Versions/3.14/Python"
if [[ -f "$PYTHON_LIB" ]]; then
    install_name_tool -id "@rpath/Python.framework/Versions/3.14/Python" "$PYTHON_LIB" 2>/dev/null || true
    codesign --force --sign - "$PYTHON_LIB" 2>/dev/null || true
fi

# Add rpath to python3.14 executable
PYTHON_EXE="$PYTHON_FW_DEST/Versions/3.14/bin/python3.14"
if [[ -f "$PYTHON_EXE" ]]; then
    install_name_tool -add_rpath "@loader_path/../../.." "$PYTHON_EXE" 2>/dev/null || true
fi

# Fix all binaries in Python framework
find "$PYTHON_FW_DEST" -type f \( -name "*.dylib" -o -name "*.so" -o -perm +111 \) -print0 2>/dev/null | \
    while IFS= read -r -d '' file; do
        fix_library_paths "$file"
    done

# Special fix for all Resources/Python.app/Contents/MacOS/Python instances
find "$PYTHON_FW_DEST" -path "*/Resources/Python.app/Contents/MacOS/Python" -type f | while read -r python_app; do
    install_name_tool -change "@loader_path/../Python" "@loader_path/../../../../Python" "$python_app" 2>/dev/null || true
    codesign --force --sign - "$python_app" 2>/dev/null || true
done

# Fix all bundled libraries
info "Fixing bundled library paths"
for lib in "$FRAMEWORKS_DIR"/*.dylib; do
    [[ -f "$lib" ]] && fix_library_paths "$lib"
done

# Fix Python _sqlite3 module to use bundled sqlite
SQLITE_MODULE="$PYTHON_FW_DEST/Versions/3.14/lib/python3.14/lib-dynload/_sqlite3.cpython-314-darwin.so"
if [[ -f "$SQLITE_MODULE" ]]; then
    install_name_tool -change "/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib" \
        "@executable_path/../Frameworks/libsqlite3.dylib" \
        "$SQLITE_MODULE" 2>/dev/null || true
    codesign --force --sign - "$SQLITE_MODULE" 2>/dev/null || true
fi

# Step 6: Create standalone launcher
info "Step 6/7: Creating standalone launcher"

cat > "$MACOS_DIR/meshy" << 'LAUNCHER_EOF'
#!/bin/bash
# Meshy standalone launcher - fully self-contained

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONTENTS="$DIR/.."
RESOURCES="$CONTENTS/Resources"
FRAMEWORKS="$CONTENTS/Frameworks"

# Python environment
export PYTHONHOME="$FRAMEWORKS/Python.framework/Versions/3.14"
export PYTHONPATH="$RESOURCES/lib/python:$RESOURCES/lib/python-packages:$PYTHONHOME/lib/python3.14:$PYTHONHOME/lib/python3.14/lib-dynload"

# GTK environment
export DYLD_LIBRARY_PATH="$FRAMEWORKS:$DYLD_LIBRARY_PATH"
export GI_TYPELIB_PATH="$RESOURCES/lib/girepository-1.0"
export XDG_DATA_DIRS="$RESOURCES/share:/usr/local/share:/usr/share"
export GTK_DATA_PREFIX="$RESOURCES"
export GTK_EXE_PREFIX="$RESOURCES"
export GTK_PATH="$RESOURCES"

# Force GTK to use macOS backend
export GDK_BACKEND=macos

# GDK Pixbuf
export GDK_PIXBUF_MODULEDIR="$RESOURCES/lib/gdk-pixbuf-2.0/2.10.0/loaders"
export GDK_PIXBUF_MODULE_FILE="$RESOURCES/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache"

# Use fontconfig backend instead of CoreText to prevent emoji crashes (Bus error 10)
# Workaround for Pango issue #871 - CoreText emoji rendering crashes on macOS
# See: https://gitlab.gnome.org/GNOME/pango/-/work_items/871
export PANGOCAIRO_BACKEND=fc

# Meshy specific
export MESHY_PKGDATADIR="$RESOURCES/share/meshy"

# Use bundled Python
PYTHON="$FRAMEWORKS/Python.framework/Versions/3.14/bin/python3.14"

exec "$PYTHON" "$RESOURCES/lib/python/meshy/__main__.py" "$@"
LAUNCHER_EOF

chmod +x "$MACOS_DIR/meshy"

# Create Python entry point
cat > "$RESOURCES_DIR/lib/python/meshy/__main__.py" << 'PYTHON_EOF'
#!/usr/bin/env python3
import os
import sys
import gettext

print("Starting Meshy from bundled __main__.py", file=sys.stderr)

# Set up package data directory
pkgdatadir = os.environ.get('MESHY_PKGDATADIR', '/usr/share/meshy')
localedir = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'share', 'locale')

# Initialize gettext for translations (sets up global _ function)
gettext.install('meshy', localedir)

# Initialize meshy package globals
import meshy as _meshy_pkg
_meshy_pkg.pkgdatadir = pkgdatadir
_meshy_pkg.QR_SCANNER_ENABLED = False  # Not available on macOS yet
_meshy_pkg.SHORTCUTS_DIALOG_ENABLED = True

# Enable minimal GTK debug output
# os.environ['GTK_DEBUG'] = 'all'  # Disabled - too verbose
# os.environ['G_MESSAGES_DEBUG'] = 'all'  # Disabled - too verbose

# Verify GObject Introspection can load macOS backend
import gi
gi.require_version("Gtk", "4.0")
try:
    gi.require_version("GdkMacos", "4.0")
    print("✓ GdkMacos backend loaded successfully", file=sys.stderr)
except ValueError as e:
    print(f"✗ CRITICAL: Cannot load GdkMacos backend: {e}", file=sys.stderr)
    print(f"  GI_TYPELIB_PATH={os.environ.get('GI_TYPELIB_PATH', 'NOT SET')}", file=sys.stderr)
    sys.exit(1)

# Import GTK and verify initialization
from gi.repository import Gtk, Gio
print(f"✓ GTK imported, version: {Gtk.get_major_version()}.{Gtk.get_minor_version()}.{Gtk.get_micro_version()}", file=sys.stderr)

# Load GResource file
gresource_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'share', 'meshy', 'meshy.gresource')
if os.path.exists(gresource_path):
    resource = Gio.Resource.load(gresource_path)
    Gio.resources_register(resource)
    print(f"✓ Loaded GResource from {gresource_path}", file=sys.stderr)
else:
    print(f"✗ WARNING: GResource not found at {gresource_path}", file=sys.stderr)

from meshy.main import main

if __name__ == '__main__':
    print("Calling meshy.main.main()", file=sys.stderr)
    sys.exit(main('$VERSION'))
PYTHON_EOF

# Step 7: Code sign the entire bundle
info "Step 7/7: Code signing bundle"

# Remove Python.app bundles BEFORE signing (not needed for our use, cause signing issues)
info "Removing Python.app bundles..."
find "$PYTHON_FW_DEST" -name "Python.app" -type d -print -exec rm -rf {} + 2>/dev/null || true

if [[ -n "$SIGN_IDENTITY" ]]; then
    info "Signing with identity: $SIGN_IDENTITY"

    # Remove all existing signatures from Python.framework (came from Homebrew)
    # This prevents "sealed resource modified" errors when we sign internal files
    info "Removing existing Python.framework signatures..."
    codesign --remove-signature "$PYTHON_FW_DEST/Python" 2>/dev/null || true
    codesign --remove-signature "$PYTHON_FW_DEST/Versions/3.14/Python" 2>/dev/null || true
    find "$PYTHON_FW_DEST" -name "*.dylib" -o -name "*.so" | while read -r lib; do
        codesign --remove-signature "$lib" 2>/dev/null || true
    done

    # Sign all .so files and dylibs in Python packages (required for notarization)
    info "Signing Python native extensions..."
    find "$RESOURCES_DIR/lib/python-packages" -type f \( -name "*.so" -o -name "*.dylib" \) 2>/dev/null | while read -r lib; do
        codesign --force --sign "$SIGN_IDENTITY" --timestamp --options runtime "$lib" 2>/dev/null || true
    done

    # Sign GDK Pixbuf loaders (.so and .dylib files)
    info "Signing GDK Pixbuf loaders..."
    find "$RESOURCES_DIR/lib/gdk-pixbuf-2.0" -type f \( -name "*.so" -o -name "*.dylib" \) 2>/dev/null | while read -r lib; do
        codesign --force --sign "$SIGN_IDENTITY" --timestamp --options runtime "$lib" 2>/dev/null || true
    done

    # Sign all binaries in Python framework (dylibs, .so files, .a files, executables)
    info "Signing Python framework binaries..."
    find "$PYTHON_FW_DEST" -type f \( -name "*.dylib" -o -name "*.so" -o -name "*.a" -o -perm +111 \) 2>/dev/null | while read -r binary; do
        # Skip if it's a text file or script
        if file "$binary" | grep -q "Mach-O"; then
            codesign --force --sign "$SIGN_IDENTITY" --timestamp --options runtime "$binary" 2>/dev/null || true
        fi
    done

    # Sign all bundled libraries
    info "Signing bundled libraries..."
    for lib in "$FRAMEWORKS_DIR"/*.dylib; do
        [[ -f "$lib" ]] && codesign --force --sign "$SIGN_IDENTITY" --timestamp --options runtime "$lib" || warn "Failed to sign $lib"
    done

    # Skip Python.framework bundle signing due to bundle format ambiguity
    # All binaries inside are already signed, which is sufficient for notarization
    info "Skipping Python.framework bundle signature (all contents already signed)"

    # Sign the entire app bundle (do NOT use --deep to avoid Python.framework ambiguity)
    info "Signing app bundle..."
    codesign --force --sign "$SIGN_IDENTITY" --timestamp --options runtime "$APP_DIR" || error "Failed to sign app bundle"

    info "✓ Bundle signed successfully"
else
    info "Skipping code signing (use --sign to enable)"
fi

# Clean up
info "Cleaning up temporary files"
find "$APP_DIR" -name "*.pyc" -delete
find "$APP_DIR" -name "__pycache__" -type d -delete

# Calculate bundle size
BUNDLE_SIZE=$(du -sh "$APP_DIR" | awk '{print $1}')

info ""
info "✅ Self-contained bundle created successfully!"
info ""
info "Bundle size: $BUNDLE_SIZE"
info "Location: $APP_DIR"
info ""
info "The app is now fully self-contained with:"
info "  • Python 3.14 interpreter"
info "  • GTK4 and libadwaita frameworks"
info "  • All Python dependencies"
info "  • All required libraries"
info ""
info "To test:"
info "  open $APP_DIR"
info ""

# Create DMG if requested
if [[ "$CREATE_DMG" == "true" ]]; then
    info "Creating DMG installer..."
    DMG_NAME="Meshy-${VERSION}.dmg"
    DMG_PATH="dist/$DMG_NAME"

    hdiutil create -volname "Meshy ${VERSION}" -srcfolder "$APP_DIR" -ov -format UDZO "$DMG_PATH"

    # Sign DMG if identity provided
    if [[ -n "$SIGN_IDENTITY" ]]; then
        info "Signing DMG..."
        codesign --force --sign "$SIGN_IDENTITY" --timestamp "$DMG_PATH" || warn "Failed to sign DMG"
    fi

    DMG_SIZE=$(du -sh "$DMG_PATH" | awk '{print $1}')
    info ""
    info "✅ DMG created: $DMG_PATH ($DMG_SIZE)"
    info ""
    info "Distribution naming convention:"
    info "  Stable release:   Meshy-26.06.dmg (from tag)"
    info "  Unstable/Nightly: Meshy-26.06.19.dmg (date version)"
    info ""
else
    info "To create DMG for distribution:"
    info "  $0 --dmg"
    info "  Or manually: hdiutil create -volname 'Meshy ${VERSION}' -srcfolder $APP_DIR -ov -format UDZO dist/Meshy-${VERSION}.dmg"
    info ""
fi
