#!/usr/bin/env bash
# ============================================================================
# V3Q.AI — Package for Distribution
# Creates a clean zip file ready to deploy on a target machine.
#
# Usage:
#   chmod +x scripts/package.sh
#   ./scripts/package.sh
#
# Output: v3q-ai-<version>.zip in the parent directory
# ============================================================================

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJECT_ROOT"

# Read version from app.yaml
VERSION=$(grep 'version:' config/app.yaml | head -1 | sed 's/.*"\(.*\)".*/\1/' || echo "1.0.0")
ZIPNAME="v3q-ai-${VERSION}.zip"
OUTPUT="../${ZIPNAME}"

echo "============================================"
echo "  V3Q.AI — Packaging v${VERSION}"
echo "============================================"
echo ""

# Build frontend first
echo "[1/3] Building frontend..."
cd frontend
if [ -d "node_modules" ]; then
    npx vite build 2>&1 | tail -3
else
    echo "  Installing npm dependencies first..."
    npm install --loglevel=warn 2>&1 | tail -2
    npx vite build 2>&1 | tail -3
fi
cd "$PROJECT_ROOT"
echo "  Frontend built."

# Create zip
echo ""
echo "[2/3] Creating ${ZIPNAME}..."

cd "$PROJECT_ROOT/.."
DIRNAME=$(basename "$PROJECT_ROOT")

zip -r "$ZIPNAME" "$DIRNAME" \
    -x "${DIRNAME}/backend/.venv/*" \
    -x "${DIRNAME}/backend/__pycache__/*" \
    -x "${DIRNAME}/backend/**/__pycache__/*" \
    -x "${DIRNAME}/frontend/node_modules/*" \
    -x "${DIRNAME}/data/*" \
    -x "${DIRNAME}/logs/*" \
    -x "${DIRNAME}/v3q_pgdata/*" \
    -x "${DIRNAME}/.git/*" \
    -x "${DIRNAME}/**/.DS_Store" \
    -x "${DIRNAME}/config/.env" \
    -x "*.pyc" \
    -x "*__pycache__*" \
    2>&1 | tail -3

cd "$PROJECT_ROOT"

ZIPSIZE=$(ls -lh "../${ZIPNAME}" | awk '{print $5}')
echo ""
echo "[3/3] Done!"
echo ""
echo "============================================"
echo "  Package: ../${ZIPNAME} (${ZIPSIZE})"
echo "============================================"
echo ""
echo "  To deploy on target machine:"
echo ""
echo "    1. Copy ${ZIPNAME} to the target server"
echo "    2. unzip ${ZIPNAME}"
echo "    3. cd middleware"
echo "    4. chmod +x scripts/setup.sh"
echo "    5. ./scripts/setup.sh"
echo ""
echo "  The setup script handles everything:"
echo "    - Detects prerequisites"
echo "    - Sets up PostgreSQL (Docker or native)"
echo "    - Creates Python venv + installs deps"
echo "    - Builds frontend"
echo "    - Runs schema migration"
echo "    - Preflight checks"
echo ""
