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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SRC_ADDON_DIR="${ROOT_DIR}/addon"
INSTALL_DIR="${ROOT_DIR}/dist"

ADDON_XML="${SRC_ADDON_DIR}/addon.xml"
if [[ ! -f "${ADDON_XML}" ]]; then
  echo "Missing: ${ADDON_XML}" >&2
  exit 1
fi

ADDON_ID="$(python3 - "${ADDON_XML}" <<'PY'
import sys
import xml.etree.ElementTree as ET

tree = ET.parse(sys.argv[1])
root = tree.getroot()
print(root.attrib.get("id", "plugin.unknown"))
PY
)"

DEST_DIR="${INSTALL_DIR}/${ADDON_ID}"

mkdir -p "${INSTALL_DIR}"
rm -rf "${DEST_DIR}"
mkdir -p "${DEST_DIR}"

# Copy add-on files (single source of truth: addon/)
if command -v rsync >/dev/null 2>&1; then
  rsync -a --delete \
    --exclude '__pycache__/' \
    --exclude '*.pyc' \
    "${SRC_ADDON_DIR}/" "${DEST_DIR}/"
else
  cp -a "${SRC_ADDON_DIR}/." "${DEST_DIR}/"
  find "${DEST_DIR}" -type d -name '__pycache__' -prune -exec rm -rf {} + || true
  find "${DEST_DIR}" -type f -name '*.pyc' -delete || true
fi

echo "${DEST_DIR}"
