#!/usr/bin/env bash
# Empaqueta el proyecto para Envato / comprador: sin dependencias ni secretos.
# Genera un ZIP estándar (Python 3 + zipfile; sin node_modules ni vendor).
#
# Uso:
#   ./scripts/package-envato.sh
#   ./scripts/package-envato.sh --name mi-producto
#   ./scripts/package-envato.sh --dry-run
#   ./scripts/package-envato.sh --exclude-frontend-build
#
# Requisitos: bash, python3 (stdlib).

set -euo pipefail

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

NAME="indicadores-envato"
DRY_RUN=0
EXCLUDE_FRONTEND_BUILD=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --name)
      NAME="${2:?}"
      shift 2
      ;;
    --dry-run)
      DRY_RUN=1
      shift
      ;;
    --exclude-frontend-build)
      EXCLUDE_FRONTEND_BUILD=1
      shift
      ;;
    -h|--help)
      cat <<'EOF'
Uso: ./scripts/package-envato.sh [opciones]

  --name NOMBRE              Prefijo del ZIP (default: indicadores-envato)
  --dry-run                  Lista archivos que entrarían en el ZIP (sin crearlo)
  --exclude-frontend-build   No incluye public/build (el comprador debe ejecutar npm run build)
  -h, --help                 Esta ayuda
EOF
      exit 0
      ;;
    *)
      echo "Opción desconocida: $1" >&2
      exit 1
      ;;
  esac
done

STAMP="$(date +%Y%m%d-%H%M)"
OUT_DIR="$ROOT/dist"
OUT_ZIP="$OUT_DIR/${NAME}-${STAMP}.zip"

EXCLUDE_BUILD_FLAG=0
if [[ "$EXCLUDE_FRONTEND_BUILD" -eq 1 ]]; then
  EXCLUDE_BUILD_FLAG=1
fi

if [[ "$DRY_RUN" -eq 1 ]]; then
  python3 - "$ROOT" "$EXCLUDE_BUILD_FLAG" <<'PY'
import os, sys
root = sys.argv[1]
exclude_build = sys.argv[2] == "1"
skip_dir_names = {
    ".git", "node_modules", "vendor", "dist", "storage",
    ".idea", ".phpunit.cache", "coverage",
}
for dirpath, dirnames, filenames in os.walk(root, topdown=True):
    rel = os.path.relpath(dirpath, root)
    parts = () if rel in (".", "") else tuple(rel.split(os.sep))
    dirnames[:] = [d for d in dirnames if d not in skip_dir_names]
    if exclude_build and parts[:2] == ("public", "build"):
        dirnames[:] = []
        continue
    for name in sorted(filenames):
        p = os.path.join(dirpath, name)
        rp = os.path.relpath(p, root)
        if rp == ".env":
            continue
        if rp.startswith(".env.") and rp != ".env.example":
            continue
        if rp == "public/hot":
            continue
        if rp.startswith(".phpunit.result.cache"):
            continue
        if name in (".DS_Store", "Thumbs.db"):
            continue
        if exclude_build and (rp.startswith("public/build" + os.sep) or rp == "public/build"):
            continue
        print(rp)
PY
  echo "(dry-run) No se creó ningún ZIP."
  exit 0
fi

mkdir -p "$OUT_DIR"

python3 - "$ROOT" "$OUT_ZIP" "$EXCLUDE_BUILD_FLAG" <<'PY'
import os, sys, zipfile

root = os.path.abspath(sys.argv[1])
out_zip = os.path.abspath(sys.argv[2])
exclude_build = sys.argv[3] == "1"

skip_dir_names = {
    ".git", "node_modules", "vendor", "dist", "storage",
    ".idea", ".phpunit.cache", "coverage",
}

def skip_file(rel_posix: str) -> bool:
    base = rel_posix.rsplit("/", 1)[-1]
    if base in (".DS_Store", "Thumbs.db"):
        return True
    if rel_posix == ".env":
        return True
    if rel_posix.startswith(".env.") and rel_posix != ".env.example":
        return True
    if rel_posix == "public/hot":
        return True
    if rel_posix.startswith(".phpunit.result.cache"):
        return True
    if rel_posix.endswith(".log"):
        return True
    if exclude_build and (rel_posix == "public/build" or rel_posix.startswith("public/build/")):
        return True
    parts = rel_posix.split("/")
    if parts and parts[0] == "storage":
        return True
    if "node_modules" in parts or "vendor" in parts:
        return True
    return False

count = 0
with zipfile.ZipFile(out_zip, "w", compression=zipfile.ZIP_DEFLATED) as zf:
    for dirpath, dirnames, filenames in os.walk(root, topdown=True):
        dirnames[:] = [d for d in dirnames if d not in skip_dir_names]
        rel_dir = os.path.relpath(dirpath, root)
        parts = () if rel_dir in (".", os.curdir) else tuple(rel_dir.split(os.sep))
        if exclude_build and parts[:2] == ("public", "build"):
            dirnames[:] = []
            continue

        for name in filenames:
            abs_path = os.path.join(dirpath, name)
            rel = os.path.relpath(abs_path, root)
            rel_posix = rel.replace(os.sep, "/")
            if skip_file(rel_posix):
                continue
            zf.write(abs_path, arcname=rel_posix)
            count += 1

print(f"Archivos añadidos al ZIP: {count}")
PY

SIZE="$(du -h "$OUT_ZIP" | cut -f1)"
echo "Listo: $OUT_ZIP ($SIZE)"
echo "Abra el ZIP y confirme que no hay .env ni JSON de Google antes de subirlo a Envato."