# Implementation Blueprint

## Backend Build Script (Python Example)

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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PYTHON_BIN="$ROOT_DIR/.venv/bin/python"
APP_NAME="TraderBackend"
BUILD_ROOT="$ROOT_DIR/dist-backend-build"
DIST_PATH="$BUILD_ROOT/dist"
WORK_PATH="$BUILD_ROOT/build"
SPEC_PATH="$BUILD_ROOT/spec"
TARGET_DIR="$ROOT_DIR/mac/TraderMac/TraderMac/EmbeddedBackend"

mkdir -p "$DIST_PATH" "$WORK_PATH" "$SPEC_PATH" "$TARGET_DIR"

"$PYTHON_BIN" -m pip install -q pyinstaller

"$PYTHON_BIN" -m PyInstaller \
  --noconfirm --clean --onefile \
  --name "$APP_NAME" \
  --distpath "$DIST_PATH" \
  --workpath "$WORK_PATH" \
  --specpath "$SPEC_PATH" \
  --add-data "$ROOT_DIR/web/app.py:." \
  --add-data "$ROOT_DIR/web/<module_dir>:<module_dir>" \
  "$ROOT_DIR/web/backend_embedded_launcher.py"

cp "$DIST_PATH/$APP_NAME" "$TARGET_DIR/$APP_NAME"
chmod +x "$TARGET_DIR/$APP_NAME"
```

## SwiftUI Host Requirements
- Use `@Observable` host object.
- Compute `serverURL` from host/port + query items.
- Start backend once on appear; stop on disappear.
- Render backend URL in `WKWebView`.
- Retry provisional load failure after short delay.
- Keep debug controls behind `#if DEBUG`.

## Settings Sync Contract
- Shared path: `~/.<app>/settings.json`
- Normalize every field on web and native sides.
- Load shared file before app launch.
- Push normalized fields as query params when launching/reloading webview.
- Persist setup-sheet changes back to shared file.

## Packaging Commands
- Build app:

```bash
./scripts/build_selfcontained_mac_app.sh
```

- Create DMG:

```bash
APP_BUNDLE_PATH="dist-mac/<timestamp>/<AppName>Mac.app" ./scripts/create_installer_dmg.sh
```

## Verification Checklist
- No external browser window opens.
- App starts with embedded backend from app resources.
- `WKWebView` loads local URL.
- Settings persist across relaunch and remain in sync.
- DMG installs and runs on a second machine.
