#!/usr/bin/env bash
# Build a CodeCanyon-friendly ZIP: Documentation/, Application/, License/
# Usage: ./scripts/build-envato-release.sh [version]
# Example: ./scripts/build-envato-release.sh 1.0.0

set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
VERSION="${1:-}"
if [[ -z "$VERSION" ]]; then
  VERSION="$(php -r "\$c = include '$ROOT/config/version.php'; echo \$c['version'] ?? '1.0.0';" 2>/dev/null || echo '1.0.0')"
fi

PKG="ProInvoice-${VERSION}"
OUT="${ROOT}/dist"
TMP="$(mktemp -d)"
DEST="${TMP}/${PKG}"

mkdir -p "${DEST}/Documentation" "${DEST}/Application" "${DEST}/License"

echo "→ Packaging ${PKG} from ${ROOT}"

# Application tree (rsync: exclude dev junk; keep .env.example)
RSYNC_EXCLUDES=(--exclude-from="${ROOT}/scripts/envato-pack-exclude.txt")
if command -v rsync >/dev/null 2>&1; then
  rsync -a "${RSYNC_EXCLUDES[@]}" "${ROOT}/" "${DEST}/Application/"
else
  echo "rsync not found; install rsync or copy files manually." >&2
  exit 1
fi

# Never ship local SQLite DBs (rsync exclude patterns vary by version)
rm -f "${DEST}/Application/database/database.sqlite" "${DEST}/Application/database/"*.sqlite 2>/dev/null || true
find "${DEST}/Application" -name "*.sqlite" -type f -delete 2>/dev/null || true

# Fresh install: never ship "already installed" marker
rm -f "${DEST}/Application/storage/app/.installed" 2>/dev/null || true

# Documentation (root markdown + /doc manual pack + optional audit)
for f in README.md INSTALLATION.md UPDATE_GUIDE.md ENVATO_SUBMISSION_CHECKLIST.md REMINDER_SYSTEM_README.md; do
  if [[ -f "${ROOT}/${f}" ]]; then
    cp "${ROOT}/${f}" "${DEST}/Documentation/"
  fi
done
if [[ -d "${ROOT}/doc" ]]; then
  mkdir -p "${DEST}/Documentation/doc"
  cp -R "${ROOT}/doc/"* "${DEST}/Documentation/doc/"
fi
if [[ -f "${ROOT}/docs/RELEASE_AUDIT.md" ]]; then
  cp "${ROOT}/docs/RELEASE_AUDIT.md" "${DEST}/Documentation/RELEASE_AUDIT.md"
fi

# License / notices
if [[ -f "${ROOT}/license/THIRD_PARTY_NOTICES.md" ]]; then
  cp "${ROOT}/license/THIRD_PARTY_NOTICES.md" "${DEST}/License/"
fi

mkdir -p "${OUT}"
ZIP_PATH="${OUT}/${PKG}.zip"
rm -f "${ZIP_PATH}"
( cd "${TMP}" && zip -r -q "${ZIP_PATH}" "${PKG}" )

rm -rf "${TMP}"

echo "✓ Created ${ZIP_PATH}"
echo "  Remind buyers: run composer install --no-dev inside Application/ (vendor is excluded)."
if [[ ! -d "${ROOT}/public/build" ]] || [[ -z "$(ls -A "${ROOT}/public/build" 2>/dev/null)" ]]; then
  echo "  Note: public/build looks empty — run npm run build before packaging if you ship compiled assets."
fi
