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

# Build macOS .app bundle for Meshy
# This script creates a relocatable macOS application bundle

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

info() {
    echo -e "${GREEN}==>${NC} $1"
}

warn() {
    echo -e "${YELLOW}Warning:${NC} $1"
}

error() {
    echo -e "${RED}Error:${NC} $1"
    exit 1
}

# Check we're on macOS
if [[ "$(uname)" != "Darwin" ]]; then
    error "This script must be run on macOS"
fi

# Check required tools
command -v meson >/dev/null 2>&1 || error "meson not found. Install with: brew install meson"
command -v ninja >/dev/null 2>&1 || error "ninja not found. Install with: brew install ninja"
command -v pkg-config >/dev/null 2>&1 || error "pkg-config not found. Install with: brew install pkg-config"

# Get version using same logic as meson.build
# 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

info "Building Meshy ${VERSION} for macOS"

# Build directory
BUILDDIR="builddir-macos"
APPDIR="dist/Meshy.app"

# Clean previous build
if [[ -d "$BUILDDIR" ]]; then
    info "Cleaning previous build directory"
    rm -rf "$BUILDDIR"
fi

if [[ -d "dist" ]]; then
    info "Cleaning previous dist directory"
    rm -rf dist
fi

# Configure with meson
info "Configuring with meson"
meson setup "$BUILDDIR" --prefix=/usr

# Build
info "Building with ninja"
meson compile -C "$BUILDDIR"

# Create app bundle structure
info "Creating app bundle structure"
mkdir -p "$APPDIR/Contents/MacOS"
mkdir -p "$APPDIR/Contents/Resources"
mkdir -p "$APPDIR/Contents/Frameworks"

# Install to temporary location
info "Installing to app bundle"
DESTDIR="$(pwd)/dist/tmp" meson install -C "$BUILDDIR"

# Copy installed files to app bundle
info "Copying application files"
# Copy the main executable
cp "dist/tmp/usr/bin/meshy" "$APPDIR/Contents/MacOS/"

# Patch the launcher script to use Homebrew Python and set up bundle environment
info "Configuring launcher script"
sed -i '' '1s|.*|#!/opt/homebrew/bin/python3|' "$APPDIR/Contents/MacOS/meshy"

# Add bundle environment setup after the imports
cat > /tmp/meshy_env_setup.txt << 'ENVEOF'

# When running from app bundle, set up environment
script_path = os.path.realpath(__file__)
macos_dir = os.path.dirname(script_path)
contents_dir = os.path.dirname(macos_dir)
resources_dir = os.path.join(contents_dir, 'Resources')

# Add bundle Python path
bundle_python_path = os.path.join(resources_dir, 'lib', 'python')
if os.path.exists(bundle_python_path):
    sys.path.insert(0, bundle_python_path)
    os.environ.setdefault('MESHY_PKGDATADIR', os.path.join(resources_dir, 'share', 'meshy'))

# Set up GTK environment variables
os.environ.setdefault('GI_TYPELIB_PATH', '/opt/homebrew/lib/girepository-1.0')
os.environ.setdefault('XDG_DATA_DIRS', f"{resources_dir}/share:/opt/homebrew/share:/usr/local/share:/usr/share")

ENVEOF

# Insert the environment setup after the "import gettext" line
sed -i '' '/^import gettext$/r /tmp/meshy_env_setup.txt' "$APPDIR/Contents/MacOS/meshy"
rm /tmp/meshy_env_setup.txt

# Copy Python sources
mkdir -p "$APPDIR/Contents/Resources/lib/python"
cp -r "dist/tmp/usr/lib/"*"/site-packages/meshy" "$APPDIR/Contents/Resources/lib/python/" 2>/dev/null || true
# Fallback: copy from source if meson install didn't copy them
if [[ ! -d "$APPDIR/Contents/Resources/lib/python/meshy" ]]; then
    cp -r src "$APPDIR/Contents/Resources/lib/python/meshy"
fi

# Copy data files
mkdir -p "$APPDIR/Contents/Resources/share/meshy"
cp -r "dist/tmp/usr/share/meshy/"* "$APPDIR/Contents/Resources/share/meshy/" 2>/dev/null || true

# Copy GSettings schemas
mkdir -p "$APPDIR/Contents/Resources/share/glib-2.0/schemas"
cp -r "dist/tmp/usr/share/glib-2.0/schemas/"* "$APPDIR/Contents/Resources/share/glib-2.0/schemas/" 2>/dev/null || true

# Copy icons
mkdir -p "$APPDIR/Contents/Resources/share/icons"
cp -r "dist/tmp/usr/share/icons/"* "$APPDIR/Contents/Resources/share/icons/" 2>/dev/null || true

# Copy app icon to Resources (macOS looks for it here)
info "Copying app icon"
if [[ -f "data/icons/hicolor/512x512/apps/page.codeberg.sesivany.Meshy.png" ]]; then
    cp "data/icons/hicolor/512x512/apps/page.codeberg.sesivany.Meshy.png" "$APPDIR/Contents/Resources/Meshy.png"
fi

# Generate Info.plist
info "Generating Info.plist"
sed "s/@VERSION@/$VERSION/g" data/macos/Info.plist.in > "$APPDIR/Contents/Info.plist"

# TODO: Copy GTK4 and libadwaita frameworks from Homebrew
# This would require bundling the frameworks or using dylibbundler
warn "GTK4/libadwaita frameworks not bundled - app requires Homebrew installation"
warn "To run: Install dependencies with 'brew install gtk4 libadwaita'"

# Compile GSettings schemas in bundle
if command -v glib-compile-schemas >/dev/null 2>&1; then
    info "Compiling GSettings schemas"
    glib-compile-schemas "$APPDIR/Contents/Resources/share/glib-2.0/schemas" 2>/dev/null || true
fi

# Clean up temporary install directory
rm -rf dist/tmp

info "App bundle created: $APPDIR"
info ""
info "To test the app:"
info "  open $APPDIR"
info ""
info "Note: This is a development bundle that requires GTK4/libadwaita from Homebrew"
info "For distribution, you would need to bundle the frameworks or use gtk-mac-bundler"
