#!/bin/bash
# Build script for macOS release binary and create .app bundle

set -e

echo "Building Markle for macOS..."

# Navigate to project root
cd "$(dirname "$0")/.."

# Clean previous builds
echo "Cleaning previous builds..."
dotnet clean MarkdownEditor.csproj -c Release

# Determine architecture
ARCH=$(uname -m)
if [ "$ARCH" = "arm64" ]; then
    RUNTIME="osx-arm64"
    echo "Building for Apple Silicon (ARM64)..."
else
    RUNTIME="osx-x64"
    echo "Building for Intel (x64)..."
fi

# Build for macOS (not as single file - we need dependencies accessible)
echo "Building application..."
dotnet publish MarkdownEditor.csproj \
    -c Release \
    -r $RUNTIME \
    --self-contained true \
    -o ./bin/Release/$RUNTIME/publish

# Create .app bundle structure
APP_NAME="OrmentiaMarkle.app"
APP_PATH="./bin/Release/$RUNTIME/$APP_NAME"
CONTENTS_PATH="$APP_PATH/Contents"
MACOS_PATH="$CONTENTS_PATH/MacOS"
RESOURCES_PATH="$CONTENTS_PATH/Resources"

echo "Creating .app bundle structure..."
rm -rf "$APP_PATH"
mkdir -p "$MACOS_PATH"
mkdir -p "$RESOURCES_PATH"

# Copy all files from publish to MacOS
echo "Copying application files..."
cp -R ./bin/Release/$RUNTIME/publish/* "$MACOS_PATH/"

# Make the executable actually executable
chmod +x "$MACOS_PATH/OrmentiaMarkle"

# Copy icon
echo "Copying application icon..."
if [ -f "./Assets/AppIcon.icns" ]; then
    cp "./Assets/AppIcon.icns" "$RESOURCES_PATH/"
else
    echo "Warning: AppIcon.icns not found, app will use default icon"
fi

# Create Info.plist
echo "Creating Info.plist..."
cat > "$CONTENTS_PATH/Info.plist" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleName</key>
    <string>Markle</string>
    <key>CFBundleDisplayName</key>
    <string>Markle</string>
    <key>CFBundleIdentifier</key>
    <string>com.ormentia.markle</string>
    <key>CFBundleVersion</key>
    <string>1.0.0</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0.0</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleSignature</key>
    <string>MRKS</string>
    <key>CFBundleExecutable</key>
    <string>OrmentiaMarkle</string>
    <key>CFBundleIconFile</key>
    <string>AppIcon.icns</string>
    <key>LSMinimumSystemVersion</key>
    <string>10.15</string>
    <key>NSHighResolutionCapable</key>
    <true/>
    <key>NSHumanReadableCopyright</key>
    <string>© 2025 Ormentia. All rights reserved.</string>
</dict>
</plist>
EOF

# Clean up publish directory
rm -rf ./bin/Release/$RUNTIME/publish

echo ""
echo "✓ Build completed successfully!"
echo "Application bundle: ./bin/Release/$RUNTIME/$APP_NAME"
echo ""
echo "You can now:"
echo "  1. Double-click the app to run it"
echo "  2. Drag it to /Applications folder"
echo "  3. Distribute the .app bundle"
echo ""

# Open Finder to the build location
open ./bin/Release/$RUNTIME

