#!/bin/bash
# ============================================================
#  Build DSH.app — the Dock-able DeepSeek Harness launcher app
#  ------------------------------------------------------------
#  What it does:
#    1. Generates the app icon (scripts/gen-icon.py, needs Pillow)
#    2. Compiles scripts/DSH.applescript into a stay-open app
#       at ~/Applications/DSH.app
#    3. Installs the icon, patches Info.plist identity, and
#       registers the app with LaunchServices
#  Result: double-click DSH.app to start the harness, Cmd+Q
#  (after confirmation) to stop it — a normal macOS app feel.
#
#  The compiled app delegates the server process to Terminal
#  (Terminal has full file-access context), so no sandbox/TCC
#  permission problems occur when reading ~/.dsh.
# ============================================================

set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(dirname "$HERE")"
APP="$HOME/Applications/DSH.app"
BUNDLE_ID="local.dsh.launcher"

command -v osacompile >/dev/null || { echo "osacompile not found"; exit 1; }

echo "==> generating icon"
python3 "$HERE/gen-icon.py"
ICNS="$ROOT/build/DSH.icns"

echo "==> compiling stay-open app -> $APP"
rm -rf "$APP"
osacompile -s -o "$APP" "$HERE/DSH.applescript"

echo "==> installing icon"
cp "$ICNS" "$APP/Contents/Resources/applet.icns"

echo "==> patching Info.plist"
PLIST="$APP/Contents/Info.plist"
/usr/libexec/PlistBuddy -c "Add :CFBundleIdentifier string $BUNDLE_ID" "$PLIST" 2>/dev/null || \
  /usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier $BUNDLE_ID" "$PLIST"
/usr/libexec/PlistBuddy -c "Add :CFBundleDisplayName string DeepSeek Harness" "$PLIST" 2>/dev/null || \
  /usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName DeepSeek Harness" "$PLIST"

echo "==> registering with LaunchServices"
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f "$APP"

echo "✅ DSH.app built at $APP"
echo "   Double-click to start the harness; Cmd+Q (with confirmation) to stop."
