#!/usr/bin/env bash
# Build, bundle, and publish CxAI ADE (CxWebAppMac) into ../share/cxai-mac/.
#
# Produces:
#   share/cxai-mac/CxAI ADE.app
#   share/cxai-mac/CxAI-ADE-<VERSION>-aarch64.app.tar.gz
#   share/cxai-mac/CxAI-ADE-<VERSION>-aarch64.dmg
#   share/cxai-mac/build-info.json
set -euo pipefail

cd "$(dirname "$0")/.."
SWIFT_APP_ROOT="$PWD"
REPO_ROOT="$(cd ../.. && pwd)"
SHARE_DIR="$REPO_ROOT/CxWebApp/share/cxai-mac"

VERSION="${VERSION:-1.2.0}"
ARCH="${ARCH:-aarch64}"
PRODUCT_NAME="CxAI ADE"
BUNDLE_ID="${BUNDLE_ID:-studio.cxai.ade}"
CHANNEL="${CHANNEL:-stable}"

STAGE="$SWIFT_APP_ROOT/build/stage"
APP_PATH="$STAGE/${PRODUCT_NAME}.app"
TGZ_NAME="CxAI-ADE-${VERSION}-${ARCH}.app.tar.gz"
DMG_NAME="CxAI-ADE-${VERSION}-${ARCH}.dmg"

echo "[1/6] swift build -c release"
swift build -c release

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

echo "[2/6] assemble bundle $APP_PATH"
rm -rf "$STAGE"
mkdir -p "$APP_PATH/Contents/MacOS" "$APP_PATH/Contents/Resources"
cp "$BIN" "$APP_PATH/Contents/MacOS/CxWebAppMac"
cat > "$APP_PATH/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>${BUNDLE_ID}</string>
  <key>CFBundleName</key>               <string>${PRODUCT_NAME}</string>
  <key>CFBundleDisplayName</key>        <string>${PRODUCT_NAME}</string>
  <key>CFBundleExecutable</key>         <string>CxWebAppMac</string>
  <key>CFBundlePackageType</key>        <string>APPL</string>
  <key>CFBundleShortVersionString</key> <string>${VERSION}</string>
  <key>CFBundleVersion</key>            <string>${VERSION}</string>
  <key>LSMinimumSystemVersion</key>     <string>13.0</string>
  <key>NSHighResolutionCapable</key>    <true/>
  <key>NSAppTransportSecurity</key>
    <dict><key>NSAllowsLocalNetworking</key><true/></dict>
  <key>LSApplicationCategoryType</key>  <string>public.app-category.developer-tools</string>
</dict></plist>
PLIST

echo "[3/6] codesign (ad-hoc)"
codesign --force --deep --sign - "$APP_PATH" >/dev/null 2>&1 || true

echo "[4/6] tar.gz"
( cd "$STAGE" && tar -czf "$TGZ_NAME" "${PRODUCT_NAME}.app" )

echo "[5/6] dmg"
DMG_TMP="$STAGE/$DMG_NAME"
rm -f "$DMG_TMP"
hdiutil create -volname "${PRODUCT_NAME} ${VERSION}" \
  -srcfolder "$APP_PATH" -ov -format UDZO -quiet \
  "$DMG_TMP"

echo "[6/6] publish -> $SHARE_DIR"
mkdir -p "$SHARE_DIR"
# Wipe any prior CxAI-ADE-* / CxAI ADE*.app set; keep folder, replace contents.
find "$SHARE_DIR" -maxdepth 1 \( -name "CxAI-ADE-*" -o -name "CxAI ADE*.app" -o -name "build-info.json" \) -exec rm -rf {} +
# Re-stage fresh artifacts.
ditto "$APP_PATH"            "$SHARE_DIR/${PRODUCT_NAME}.app"
cp    "$STAGE/$TGZ_NAME"     "$SHARE_DIR/$TGZ_NAME"
cp    "$DMG_TMP"             "$SHARE_DIR/$DMG_NAME"

# Compute hashes & sizes.
sha_tgz=$(shasum -a 256 "$SHARE_DIR/$TGZ_NAME" | awk '{print $1}')
sha_dmg=$(shasum -a 256 "$SHARE_DIR/$DMG_NAME" | awk '{print $1}')
size_dmg=$(stat -f%z "$SHARE_DIR/$DMG_NAME")
size_tgz=$(stat -f%z "$SHARE_DIR/$TGZ_NAME")
built_at=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

# Best-effort git sha (outer iCloud repo).
git_sha=$( ( cd "$REPO_ROOT" && git rev-parse --short=12 HEAD 2>/dev/null ) || echo "unknown" )

cat > "$SHARE_DIR/build-info.json" <<JSON
{
  "name": "${PRODUCT_NAME}",
  "version": "${VERSION}",
  "identifier": "${BUNDLE_ID}",
  "channel": "${CHANNEL}",
  "sha": "${git_sha}",
  "built_at": "${built_at}",
  "description": "Native AppKit/SwiftUI shell for CxAI Studio. Built from CxWebApp/swift-app (CxLLM-SDK + CxLLM-Drive).",
  "platform": "macOS 13+ ${ARCH}",
  "modules": [
    "CxCode", "CxAWS", "CxGit", "CxAgent", "CxMCP",
    "CxModels", "CxChat", "CxSPARenderer", "CxInstrument",
    "CxLangBridge", "CxARA", "CxDrive"
  ],
  "artifacts": {
    "app_tar_gz":         "${TGZ_NAME}",
    "app_tar_gz_sha256":  "${sha_tgz}",
    "app_tar_gz_size":    ${size_tgz},
    "dmg":                "${DMG_NAME}",
    "dmg_sha256":         "${sha_dmg}",
    "dmg_size_bytes":     ${size_dmg}
  },
  "download_url": "/static/cxai-mac/${DMG_NAME}"
}
JSON

echo
echo "Published to $SHARE_DIR"
ls -la "$SHARE_DIR"
