#!/usr/bin/env bash
##############################################################
# GMLM Platform — Release Package Builder
#
# Creates a distributable ZIP package with:
# - All application source files
# - Compiled frontend assets (public/build/)
# - Composer dependencies (vendor/)
# - Standalone installer
# - README and docs
#
# Usage:
#   bash scripts/package-release.sh [--version 1.2.0] [--no-vendor]
#
# Output: releases/gmlm-platform-{version}.zip
##############################################################

set -euo pipefail

VERSION=$(cat config/gmlm.php 2>/dev/null | grep "'version'" | head -1 | grep -oP "'\K[^']+(?=')" || echo "1.0.0")
INCLUDE_VENDOR=true
RELEASE_DIR="releases"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)

while [[ "$#" -gt 0 ]]; do
    case $1 in
        --version)    VERSION="$2"; shift ;;
        --no-vendor)  INCLUDE_VENDOR=false ;;
    esac
    shift
done

PACKAGE_NAME="gmlm-platform-${VERSION}"
PACKAGE_FILE="${RELEASE_DIR}/${PACKAGE_NAME}.zip"

echo ""
echo "╔══════════════════════════════════════════╗"
echo "║   GMLM Platform — Building Release       ║"
echo "╚══════════════════════════════════════════╝"
echo ""
echo "  Version:    ${VERSION}"
echo "  Package:    ${PACKAGE_FILE}"
echo "  Vendor:     ${INCLUDE_VENDOR}"
echo ""

mkdir -p "${RELEASE_DIR}"

# ── 1. Build frontend assets ─────────────────────────────────
echo "▶ Building frontend assets..."
npm run build --silent
echo "✓ Frontend assets built."

# ── 2. Optimize Composer autoloader ──────────────────────────
echo "▶ Optimizing Composer autoloader..."
composer dump-autoload --optimize --no-dev --quiet
echo "✓ Autoloader optimized."

# ── 3. Create the package ─────────────────────────────────────
echo "▶ Creating package archive..."

# Files and directories to include
INCLUDE=(
    "app/"
    "bootstrap/"
    "config/"
    "database/"
    "installer/"
    "public/"
    "resources/"
    "routes/"
    "storage/app/.gitkeep"
    "storage/framework/cache/.gitkeep"
    "storage/framework/sessions/.gitkeep"
    "storage/framework/views/.gitkeep"
    "storage/logs/.gitkeep"
    ".env.example"
    ".htaccess"
    "artisan"
    "composer.json"
    "composer.lock"
    "install.php"
    "package.json"
    "README.md"
    "INSTALL.md"
    "DISASTER_RECOVERY.md"
    "deploy.sh"
)

# Optionally include vendor/
if [[ "$INCLUDE_VENDOR" == "true" ]]; then
    INCLUDE+=("vendor/")
fi

# Build zip
zip -r "${PACKAGE_FILE}" "${INCLUDE[@]}" \
    --exclude "*.DS_Store" \
    --exclude "*/.git/*" \
    --exclude "*/node_modules/*" \
    --exclude "*/tests/*" \
    --exclude "*/.phpunit.cache/*" \
    --exclude "*/storage/logs/*.log" \
    --quiet

SIZE=$(du -sh "${PACKAGE_FILE}" | cut -f1)
echo "✓ Package created: ${PACKAGE_FILE} (${SIZE})"

# ── 4. Generate SHA-256 checksum ─────────────────────────────
sha256sum "${PACKAGE_FILE}" > "${PACKAGE_FILE}.sha256"
echo "✓ SHA-256 checksum: $(cat "${PACKAGE_FILE}.sha256" | cut -d' ' -f1)"

# ── 5. Create release notes ────────────────────────────────────
cat > "${RELEASE_DIR}/RELEASE-${VERSION}.md" << EOF
# GMLM Platform v${VERSION}

Released: $(date -u +"%Y-%m-%d %H:%M UTC")

## Installation

1. Download \`${PACKAGE_NAME}.zip\`
2. Upload to your hosting server
3. Extract the ZIP
4. Point your domain's web root to the \`public/\` directory
5. Visit your domain — the installer launches automatically
6. Follow the 5-step wizard

## Verify Download

\`\`\`bash
sha256sum -c ${PACKAGE_NAME}.zip.sha256
\`\`\`

## Requirements

- PHP 8.3+, MySQL 8.0+, Redis 7+ (optional)
- See README.md for full requirements
EOF

echo ""
echo "╔══════════════════════════════════════════╗"
echo "║   ✓ Release Package Ready                ║"
echo "╚══════════════════════════════════════════╝"
echo ""
echo "  Package: ${PACKAGE_FILE}"
echo "  Size:    ${SIZE}"
echo ""
echo "  To push to GitHub:"
echo "  bash scripts/push-to-github.sh --token YOUR_TOKEN --repo your-org/gmlm-platform --version ${VERSION}"
echo ""
