#!/usr/bin/env bash
set -u

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT_DIR"

USE_CI=0
SKIP_BUILD=0
CONTINUE_ON_ERROR=0
INSTALL_PLAYWRIGHT=0
AUDIT_FIX=0

for arg in "$@"; do
  case "$arg" in
    --ci) USE_CI=1 ;;
    --skip-build) SKIP_BUILD=1 ;;
    --continue-on-error) CONTINUE_ON_ERROR=1 ;;
    --install-playwright) INSTALL_PLAYWRIGHT=1 ;;
    --audit-fix) AUDIT_FIX=1 ;;
    *)
      echo "Argomento non riconosciuto: $arg"
      echo "Uso: ./setup.sh [--ci] [--skip-build] [--continue-on-error] [--install-playwright] [--audit-fix]"
      exit 2
      ;;
  esac
done

if ! command -v node >/dev/null 2>&1; then
  echo "node non trovato nel PATH"
  exit 1
fi

if ! command -v npm >/dev/null 2>&1; then
  echo "npm non trovato nel PATH"
  exit 1
fi

mapfile -t module_dirs < <(
  {
    [ -f "$ROOT_DIR/package.json" ] && echo "$ROOT_DIR"
    find "$ROOT_DIR" -mindepth 1 -maxdepth 1 -type d -exec test -f "{}/package.json" \; -print
  } | sort -u
)

if [ "${#module_dirs[@]}" -eq 0 ]; then
  echo "Nessun package.json trovato."
  exit 0
fi

echo "Trovati ${#module_dirs[@]} moduli con package.json"

failed_modules=()

for dir in "${module_dirs[@]}"; do
  echo
  echo "> Modulo: $dir"
  pushd "$dir" >/dev/null || {
    failed_modules+=("$dir")
    [ "$CONTINUE_ON_ERROR" -eq 1 ] && continue || break
  }

  had_error=0

  if [ "$USE_CI" -eq 1 ] && [ -f "package-lock.json" ]; then
    npm ci --no-fund --no-audit || had_error=1
  else
    npm install --no-fund --no-audit || had_error=1
  fi

  if [ "$AUDIT_FIX" -eq 1 ]; then
    npm audit fix --no-fund || had_error=1
  fi

  if [ "$SKIP_BUILD" -eq 0 ]; then
    npm run build --if-present || had_error=1
  fi

  popd >/dev/null || true

  if [ "$had_error" -eq 1 ]; then
    failed_modules+=("$dir")
    if [ "$CONTINUE_ON_ERROR" -ne 1 ]; then
      break
    fi
  fi
done

if [ "$INSTALL_PLAYWRIGHT" -eq 1 ] && [ -f "$ROOT_DIR/playwright-node/package.json" ]; then
  echo
  echo "> Installazione browser Playwright (chromium)"
  pushd "$ROOT_DIR/playwright-node" >/dev/null || failed_modules+=("$ROOT_DIR/playwright-node")
  if ! npx playwright install chromium; then
    failed_modules+=("$ROOT_DIR/playwright-node (playwright install chromium)")
  fi
  popd >/dev/null || true
fi

if [ "${#failed_modules[@]}" -gt 0 ]; then
  echo
  echo "Moduli con errore:"
  for module in "${failed_modules[@]}"; do
    echo "- $module"
  done
  exit 1
fi

echo
echo "Setup completato con successo."
