#!/bin/bash
# Package System Upgrade — dev or prod
# Usage: bash package_system.sh dev <version>
#        bash package_system.sh prod <version>
set -euo pipefail

TARGET="${1:?Usage: $0 <dev|prod> <version>}"
VERSION="${2:?Usage: $0 <dev|prod> <version>}"
PROJECT="/Users/accusys/momentry_core_0.1"
OUTPUT="$PROJECT/release/system/$TARGET/$VERSION"
PG_BIN="/Users/accusys/pgsql/18.3/bin"
T0=$(date +%s)

case "$TARGET" in
  dev)
    SCHEMA="dev"
    ENV_FILE=".env.development"
    ;;
  prod)
    SCHEMA="public"
    ENV_FILE=".env"
    ;;
  *)
    echo "Target must be 'dev' or 'prod'"
    exit 1
    ;;
esac

mkdir -p "$OUTPUT/scripts" "$OUTPUT/test" "$OUTPUT/migration" "$OUTPUT/portal"

echo "=== System Package (${TARGET}) ${VERSION} ==="

# 1. Source code
echo "[1/6] Source code (git archive)..."
cd "$PROJECT"
git archive --format=tar.gz -o "$OUTPUT/source.tar.gz" HEAD 2>/dev/null
echo "  $(ls -lh "$OUTPUT/source.tar.gz" | awk '{print $5}')"

# 2. Schema
echo "[2/6] Schema DDL (${SCHEMA})..."
$PG_BIN/pg_dump -U accusys -d momentry --schema="$SCHEMA" --schema-only > "$OUTPUT/schema.sql" 2>/dev/null
echo "  $(ls -lh "$OUTPUT/schema.sql" | awk '{print $5}')"

# 3. Scripts (tools)
echo "[3/6] Tools & scripts..."
for s in pipeline_status.py generate_asr1.py apply_asr_corrections.py clean_sentence_text.py import_file_package.py; do
  if [ -f "$PROJECT/scripts/$s" ]; then
    cp "$PROJECT/scripts/$s" "$OUTPUT/scripts/"
    echo "  $s"
  fi
done
cp "$PROJECT/docs_v1.0/M4_HANDOVER/api_test.sh" "$OUTPUT/test/"
echo "  api_test.sh"

# 4. Portal frontend (dev only)
if [ "$TARGET" = "dev" ] && [ -d "$PROJECT/portal/dist" ]; then
  echo "[4/6] Portal frontend (dist)..."
  cp -r "$PROJECT/portal/dist" "$OUTPUT/portal/"
  echo "  dist/ ($(du -sh "$PROJECT/portal/dist" | awk '{print $1}'))"
elif [ "$TARGET" = "dev" ]; then
  echo "[4/6] Portal frontend — SKIP (no dist, run 'npm run build' first)"
fi

# 5. Env config
echo "[5/6] Environment config..."
if [ -f "$PROJECT/$ENV_FILE" ]; then
  cp "$PROJECT/$ENV_FILE" "$OUTPUT/"
  echo "  $ENV_FILE"
else
  echo "  WARN: $ENV_FILE not found"
fi

# 6. RELEASE_INFO
echo "[6/6] RELEASE_INFO..."
cat > "$OUTPUT/RELEASE_INFO.txt" << EOF
Release: ${VERSION}
Target: ${TARGET}
Schema: ${SCHEMA}
Date: $(date +%Y-%m-%d)

Contents:
  - source.tar.gz
  - schema.sql (${SCHEMA})
  - scripts/* (tools)
  - test/api_test.sh
  - ${ENV_FILE}
EOF
if [ "$TARGET" = "dev" ] && [ -d "$OUTPUT/portal/dist" ]; then
  echo "  - portal/dist/" >> "$OUTPUT/RELEASE_INFO.txt"
fi

# Symlink latest
mkdir -p "$PROJECT/release/system/$TARGET"
ln -sfn "$OUTPUT" "$PROJECT/release/system/$TARGET/latest"

ELAPSED=$(($(date +%s) - T0))
echo ""
echo "=== System Package (${TARGET}) done (${ELAPSED}s) ==="
echo "  $OUTPUT"
du -sh "$OUTPUT"