#!/bin/bash
# export_prod.sh - Generates a clean production bundle for distribution

echo "📦 Preparing TFM aInventory Production Bundle..."

# Extract version from VERSION.json using grep to avoid macOS python/xcode stubs
VERSION=$(grep '"version"' VERSION.json | head -n 1 | awk -F '"' '{print $4}')
PROD_DIR="aInventory-PROD-v${VERSION}"

# Clean previous run if it exists
rm -rf "$PROD_DIR"
rm -f "${PROD_DIR}.zip"

mkdir -p "$PROD_DIR"

echo "📂 Copying application components (excluding dev artifacts)..."
# Core application
rsync -a --exclude 'node_modules' --exclude '.next' frontend/ "$PROD_DIR/frontend/"
rsync -a --exclude '__pycache__' --exclude '.pytest_cache' --exclude '.venv' --exclude 'tests' backend/ "$PROD_DIR/backend/"

# Orchestration, Config & Scripts
cp docker-compose.yml "$PROD_DIR/"
rsync -a config/ "$PROD_DIR/config/"
cp start_server.sh "$PROD_DIR/"
cp run_standalone.sh "$PROD_DIR/"
cp install_service.sh "$PROD_DIR/"
cp inventory.service.template "$PROD_DIR/"
cp USER_GUIDE.md "$PROD_DIR/"
cp README.md "$PROD_DIR/INSTALLATION_GUIDE.md"
cp .git_path "$PROD_DIR/" 2>/dev/null || true
cp VERSION.json "$PROD_DIR/"

# Setup persistent volume skeleton
mkdir -p "$PROD_DIR/data"
mkdir -p "$PROD_DIR/logs"
# Place a README in the root of the release
cat <<EOF > "$PROD_DIR/README.txt"
TFM aInventory - v${VERSION}
=============================

This is a clean production build, free of development or AI-agent constraints.

TO RUN VIA DOCKER (Recommended):
1. Install Docker Desktop or Docker Engine.
2. Run: docker-compose build
3. Run: docker-compose up -d
4. Access via https://<YOUR-IP>:8909 (Accept the internal security warning).

TO INSTALL AS A LINUX SYSTEM SERVICE (Optional):
1. sudo ./install_service.sh
2. sudo systemctl start inventory

TO RUN BARE-METAL (No Docker):
1. Install Python 3.12+ and Node.js 20+.
2. Ensure you have network access for npm installs.
3. Run: ./start_server.sh
4. Access via https://<YOUR-IP>:8909

Note: Database and Logs will persist in the /data and /logs directories.
EOF

echo "🗜️ Zipping the final bundle..."
zip -r -q "${PROD_DIR}.zip" "$PROD_DIR"

# Optional: cleanup the directory to leave just the zip
# rm -rf "$PROD_DIR"

echo "✅ SUCCESS: The clean production archive is ready: ${PROD_DIR}.zip"
