#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"

SVG_SRC="../cue/assets/cue.svg"
ICON_DIR="CueIOS/Assets.xcassets/AppIcon.appiconset"
BUILD_DIR="build"

# Generate app icon from SVG
if [ -f "$SVG_SRC" ] && command -v rsvg-convert &>/dev/null; then
    echo "Generating app icon from $SVG_SRC"
    rsvg-convert -w 1024 -h 1024 "$SVG_SRC" -o /tmp/cue-icon-raw.png
    if command -v magick &>/dev/null; then
        magick /tmp/cue-icon-raw.png -filter Point -gravity center \
            -background none -extent 1024x1024 \
            "$ICON_DIR/appicon-1024.png"
    else
        cp /tmp/cue-icon-raw.png "$ICON_DIR/appicon-1024.png"
    fi
    rm -f /tmp/cue-icon-raw.png
    echo "App icon generated"
elif [ ! -f "$ICON_DIR/appicon-1024.png" ]; then
    echo "Warning: No app icon. Place appicon-1024.png in $ICON_DIR or install rsvg-convert."
fi

# Regenerate xcodeproj if xcodegen available
if command -v xcodegen &>/dev/null; then
    xcodegen generate --quiet
fi

mkdir -p "$BUILD_DIR"

# Build for iOS device (release)
xcodebuild \
    -project CueIOS.xcodeproj \
    -scheme CueIOS \
    -configuration Release \
    -sdk iphoneos \
    -derivedDataPath "$BUILD_DIR/DerivedData" \
    CODE_SIGN_IDENTITY="Apple Development" \
    CODE_SIGN_STYLE=Automatic \
    -quiet \
    build

APP_PATH=$(find "$BUILD_DIR/DerivedData" -name "CueIOS.app" -type d | head -1)
if [ -n "$APP_PATH" ]; then
    cp -R "$APP_PATH" "$BUILD_DIR/"
    echo "Built: $BUILD_DIR/CueIOS.app"
else
    echo "Build completed but .app not found in DerivedData"
fi
