#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SETUP_SCRIPT="$ROOT_DIR/run.sh"
BUILD_APP_SCRIPT="$ROOT_DIR/scripts/build_selfcontained_mac_app.sh"
BUILD_DMG_SCRIPT="$ROOT_DIR/scripts/create_installer_dmg.sh"
VENV_PYTHON="$ROOT_DIR/.venv/bin/python"
BUILD_DIR="${BUILD_DIR:-$ROOT_DIR/build}"
DMG_DIR="${DMG_DIR:-$BUILD_DIR/dmg}"

if [[ ! -x "$VENV_PYTHON" ]]; then
  echo "Virtual environment missing. Running setup..."
  "$SETUP_SCRIPT" --setup-only
fi

if ! command -v create-dmg >/dev/null 2>&1; then
  echo "create-dmg not found. Install with: brew install create-dmg" >&2
  exit 1
fi

app_marker="$(mktemp)"
touch "$app_marker"

echo "Building fresh self-contained app (includes embedded backend rebuild)..."
"$BUILD_APP_SCRIPT"

APP_BUNDLE_PATH="$(find "$ROOT_DIR/dist-mac" -type d -name "*.app" -newer "$app_marker" | sort | tail -n 1 || true)"
rm -f "$app_marker"

if [[ -z "$APP_BUNDLE_PATH" || ! -d "$APP_BUNDLE_PATH" ]]; then
  echo "Build succeeded but no freshly built app bundle was found in dist-mac." >&2
  exit 1
fi

dmg_marker="$(mktemp)"
touch "$dmg_marker"

echo "Packaging DMG from freshly built app:"
echo "  $APP_BUNDLE_PATH"
APP_BUNDLE_PATH="$APP_BUNDLE_PATH" "$BUILD_DMG_SCRIPT"

DMG_PATH="$(find "$DMG_DIR" -type f -name "*.dmg" -newer "$dmg_marker" | sort | tail -n 1 || true)"
rm -f "$dmg_marker"

if [[ -n "$DMG_PATH" && -f "$DMG_PATH" ]]; then
  echo "Fresh installer ready:"
  echo "  $DMG_PATH"
else
  echo "DMG packaging step completed, but new DMG path could not be auto-detected." >&2
  echo "Check: $DMG_DIR"
fi
