#!/usr/bin/env bash
# Stage only files needed to run `python -m mugi_backend` from Contents/Resources/Backend.
# Replaces copying the entire repo (which pulled in CMake probes, build/, .git metadata, etc.).
# Invoked from Xcode "Copy Backend to Bundle" — see MugiApp/project.yml and .cursor/rules/swiftui.md
set -euo pipefail

REPO_ROOT="${1:?repo root}"
DEST="${2:?destination Backend directory}"

mkdir -p "$(dirname "$DEST")"
rm -rf "$DEST"
mkdir -p "$DEST"

cd "$REPO_ROOT"

# Top-level Python modules (legacy PyObjC UI + its prefs are not used by mugi_backend / Swift)
shopt -s nullglob
for f in *.py; do
  case "$f" in
    app_pyobjc2.py | app_preferences.py) continue ;;
  esac
  cp -a "$f" "$DEST/"
done
shopt -u nullglob

# Install / bootstrap metadata
for f in \
  requirements.txt \
  requirements-headless.txt \
  requirements-mlx.txt \
  requirements-mlx-pinned.txt \
  requirements-text-evolution.txt \
  requirements-chatterbox.txt \
  mugi_config.toml.example \
  setup.py
do
  [[ -f "$f" ]] && cp -a "$f" "$DEST/"
done

RSYNC_EXCLUDES=(
  --exclude '__pycache__'
  --exclude '*.pyc'
  --exclude '.pytest_cache'
  --exclude '.mypy_cache'
  --exclude '.DS_Store'
  --exclude 'CMakeFiles'
  --exclude 'CMakeCache.txt'
  --exclude 'CTestTestfile.cmake'
  --exclude 'a.out'
)

# Python packages and template trees the backend imports at runtime
DIRS=(
  backend
  core
  tools
  mesh
  utils
  dashboard_bundled
  templates
  bundled_skills
  mcp_bridge
  messaging
  evolution
  images
  scripts
)

for d in "${DIRS[@]}"; do
  if [[ -d "$REPO_ROOT/$d" ]]; then
    mkdir -p "$DEST/$d"
    rsync -a --delete "${RSYNC_EXCLUDES[@]}" "$REPO_ROOT/$d/" "$DEST/$d/"
  else
    echo "copy_backend_bundle.sh: warning: missing directory (ok if optional): $d" >&2
  fi
done

# Tool-calling LoRA dataset (train/valid JSONL only; ~16MB)
TOOL_DS_SRC="$REPO_ROOT/training/mlx_mugi_agent_tools"
if [[ -d "$TOOL_DS_SRC" ]]; then
  TOOL_DS_DEST="$DEST/training/mlx_mugi_agent_tools"
  mkdir -p "$TOOL_DS_DEST"
  for f in train.jsonl valid.jsonl dataset_meta.json; do
    if [[ -f "$TOOL_DS_SRC/$f" ]]; then
      cp -a "$TOOL_DS_SRC/$f" "$TOOL_DS_DEST/"
    fi
  done
fi
