#!/bin/bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
APP_NAME="Anime Fighter Pro Moveset Organizer"
RUNTIME_APP="$ROOT_DIR/node_modules/electron/dist/Electron.app"
DIST_DIR="$ROOT_DIR/dist/manual"
APP_BUNDLE="$DIST_DIR/$APP_NAME.app"
APP_ROOT="$APP_BUNDLE/Contents/Resources/app"
PLIST_PATH="$APP_BUNDLE/Contents/Info.plist"
ICON_SOURCE="$ROOT_DIR/assets/app-icons/notes.icns"
ICON_TARGET_NAME="anime-fighter-pro-organizer.icns"

if [[ ! -d "$RUNTIME_APP" ]]; then
  echo "Electron runtime not found at $RUNTIME_APP" >&2
  echo "Run npm install before building the Mac app." >&2
  exit 1
fi

mkdir -p "$DIST_DIR"
rm -rf "$APP_BUNDLE"
cp -R "$RUNTIME_APP" "$APP_BUNDLE"
mkdir -p "$APP_ROOT"

rsync -a \
  --delete \
  --exclude ".git" \
  --exclude "scripts" \
  --exclude "README.md" \
  "$ROOT_DIR/desktop" \
  "$ROOT_DIR/src" \
  "$ROOT_DIR/public" \
  "$ROOT_DIR/data" \
  "$ROOT_DIR/storage" \
  "$ROOT_DIR/package.json" \
  "$APP_ROOT/"

/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName $APP_NAME" "$PLIST_PATH" >/dev/null
/usr/libexec/PlistBuddy -c "Set :CFBundleName $APP_NAME" "$PLIST_PATH" >/dev/null
/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier com.animefighterpro.movesetorganizer" "$PLIST_PATH" >/dev/null
/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString 0.1.0" "$PLIST_PATH" >/dev/null
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion 0.1.0" "$PLIST_PATH" >/dev/null
if [[ -f "$ICON_SOURCE" ]]; then
  cp "$ICON_SOURCE" "$APP_BUNDLE/Contents/Resources/$ICON_TARGET_NAME"
  /usr/libexec/PlistBuddy -c "Set :CFBundleIconFile $ICON_TARGET_NAME" "$PLIST_PATH" >/dev/null
fi

PLIST_BUDDY=/usr/libexec/PlistBuddy
$PLIST_BUDDY -c "Delete :ElectronTeamID" "$PLIST_PATH" >/dev/null 2>&1 || true

cat > "$APP_ROOT/package.json" <<PKG
{
  "name": "anime-fighter-pro-moveset-organizer",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "main": "desktop/notes-main.js",
  "dependencies": {
    "express": "^5.1.0",
    "multer": "^2.0.2"
  }
}
PKG

(cd "$APP_ROOT" && npm install --omit=dev --ignore-scripts --no-audit --no-fund >/dev/null)

echo "Built: $APP_BUNDLE"
