#!/usr/bin/env bash
#
# build-macos-client.sh — build the macOS AppKit client (VoiceCatMac.app) and
# stage it into dist/macos-client/.
#
# Two steps:
#   1. Build VoiceCatCore.xcframework (macOS slice) by invoking the existing
#      clients/apple/scripts/build-xcframework.sh — that builds libvoicecat.a
#      (apple-dev preset), merges vcpkg deps into a fat .a, and stitches the
#      XCFramework the Swift Package consumes.
#   2. xcodebuild the VoiceCatMac scheme into a known derivedDataPath, then
#      copy VoiceCatMac.app into dist/macos-client/.
#
# Usage:
#   scripts/build-macos-client.sh              # build + stage into ./dist/macos-client
#   scripts/build-macos-client.sh --dist /out
#   scripts/build-macos-client.sh --no-configure   # skip cmake configure (xcframework step)
#   scripts/build-macos-client.sh --config Debug   # Xcode build config (default Release)
#   scripts/build-macos-client.sh -h|--help
#
# macOS only. Requires VCPKG_ROOT and Xcode.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VC_SCRIPT_NAME="build-macos-client"
source "$SCRIPT_DIR/common.sh"

DO_CONFIGURE=true
XCODE_CONFIG="Release"
while [[ $# -gt 0 ]]; do
    case "$1" in
        --dist)         vc_set_dist "$2"; shift 2 ;;
        --no-configure) DO_CONFIGURE=false; shift ;;
        --config)       XCODE_CONFIG="$2"; shift 2 ;;
        -h|--help)      vc_print_help "$0"; exit 0 ;;
        *) vc_die "unknown arg: $1 (try --help)" ;;
    esac
done

vc_require_macos
vc_log "dist dir: $VC_DIST_DIR"

vc_step "build VoiceCatCore.xcframework (macOS slice)"
XCFW_ARGS=()
$DO_CONFIGURE || XCFW_ARGS+=( --no-configure )
"$VC_REPO_ROOT/clients/apple/scripts/build-xcframework.sh" "${XCFW_ARGS[@]}"
XCFW="$VC_REPO_ROOT/clients/apple/VoiceCatCore.xcframework"
[[ -d "$XCFW" ]] || vc_die "xcframework not found at $XCFW"
vc_ok "xcframework ready -> $XCFW"

vc_step "xcodebuild VoiceCatMac ($XCODE_CONFIG)"
XCODEPROJ="$VC_REPO_ROOT/clients/apple/macOS/VoiceCatMac.xcodeproj"
DERIVED="$VC_REPO_ROOT/build/macos-app"
xcodebuild -project "$XCODEPROJ" -scheme VoiceCatMac \
    -configuration "$XCODE_CONFIG" -derivedDataPath "$DERIVED" build

APP="$DERIVED/Build/Products/$XCODE_CONFIG/VoiceCatMac.app"
[[ -d "$APP" ]] || vc_die "VoiceCatMac.app not found at $APP"
vc_ok "built -> $APP"

vc_step "stage -> $VC_DIST_DIR/macos-client"
STAGE="$(vc_dist_subdir macos-client)"
cp -R "$APP" "$STAGE/"
vc_ok "VoiceCatMac.app -> $STAGE/ ($(du -sh "$APP" | cut -f1))"
vc_ok "done -> $STAGE"
