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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
MAC_SRC_DIR="${MAC_SRC_DIR:-$ROOT_DIR/mac/src}"
PROJECT_PATH="${MAC_PROJECT_PATH:-}"
SCHEME="${MAC_SCHEME:-}"
CONFIGURATION="${CONFIGURATION:-Release}"
DERIVED_DATA_PATH="$ROOT_DIR/dist-mac/derived-data"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
OUTPUT_DIR="$ROOT_DIR/dist-mac/$TIMESTAMP"

discover_scheme() {
  local project_path="$1"
  python3 - "$project_path" <<'PY'
import json
import subprocess
import sys

project = sys.argv[1]
try:
    output = subprocess.check_output(
        ["xcodebuild", "-list", "-project", project, "-json"],
        text=True,
        stderr=subprocess.DEVNULL,
    )
    payload = json.loads(output)
except Exception:
    print("")
    raise SystemExit(0)

project_data = payload.get("project", {})
schemes = project_data.get("schemes") or []
print(schemes[0] if schemes else "")
PY
}

"$ROOT_DIR/scripts/build_embedded_backend.sh"

if [[ -z "$PROJECT_PATH" ]]; then
  PROJECT_PATH="$(find "$MAC_SRC_DIR" -maxdepth 4 -name "*.xcodeproj" | sort | head -n 1)"
fi
if [[ -z "$PROJECT_PATH" ]]; then
  echo "No .xcodeproj found under: $MAC_SRC_DIR" >&2
  echo "Set MAC_PROJECT_PATH to the project you want to build." >&2
  exit 1
fi
if [[ -z "$SCHEME" ]]; then
  SCHEME="$(discover_scheme "$PROJECT_PATH")"
fi
if [[ -z "$SCHEME" ]]; then
  SCHEME="$(basename "$PROJECT_PATH" .xcodeproj)"
fi

xcodebuild \
  -project "$PROJECT_PATH" \
  -scheme "$SCHEME" \
  -configuration "$CONFIGURATION" \
  -derivedDataPath "$DERIVED_DATA_PATH" \
  build

APP_PATH="$(find "$DERIVED_DATA_PATH/Build/Products/$CONFIGURATION" -maxdepth 2 -name "${SCHEME}.app" | head -n 1)"
if [[ -z "${APP_PATH:-}" ]]; then
  echo "Build failed: ${SCHEME}.app not found in build products." >&2
  exit 1
fi

mkdir -p "$OUTPUT_DIR"
cp -R "$APP_PATH" "$OUTPUT_DIR/"

echo "Self-contained app created: $OUTPUT_DIR/${SCHEME}.app"
echo "To package DMG:"
echo "APP_BUNDLE_PATH=\"$OUTPUT_DIR/${SCHEME}.app\" ./scripts/create_installer_dmg.sh"
