#!/usr/bin/env bash
# Build CxWebAppMac.app from the SwiftPM target.
set -euo pipefail

cd "$(dirname "$0")/.."

CONFIG="${CONFIG:-release}"
APP="CxWebAppMac.app"
DST="build/$APP"

echo "[1/3] swift build -c $CONFIG"
swift build -c "$CONFIG"

BIN=$(swift build -c "$CONFIG" --show-bin-path)/CxWebAppMac
[[ -x "$BIN" ]] || { echo "FATAL: $BIN not found" >&2; exit 1; }

echo "[2/3] assemble bundle at $DST"
rm -rf "$DST"
mkdir -p "$DST/Contents/MacOS" "$DST/Contents/Resources"
cp "$BIN" "$DST/Contents/MacOS/CxWebAppMac"
cat > "$DST/Contents/Info.plist" <<'PLIST'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>CFBundleIdentifier</key>      <string>studio.cxai.cxwebapp.mac</string>
  <key>CFBundleName</key>            <string>CxWebApp</string>
  <key>CFBundleExecutable</key>      <string>CxWebAppMac</string>
  <key>CFBundlePackageType</key>     <string>APPL</string>
  <key>CFBundleShortVersionString</key> <string>1.1.0</string>
  <key>CFBundleVersion</key>         <string>1</string>
  <key>LSMinimumSystemVersion</key>  <string>13.0</string>
  <key>NSHighResolutionCapable</key> <true/>
  <key>NSAppTransportSecurity</key>
    <dict><key>NSAllowsLocalNetworking</key><true/></dict>
</dict></plist>
PLIST

echo "[3/3] codesign (ad-hoc, no notarization)"
codesign --force --sign - "$DST" 2>/dev/null || true

echo
echo "Built: $DST"
echo "Run:   open '$DST'  (or: '$DST/Contents/MacOS/CxWebAppMac')"
