#!/usr/bin/env bash
# ----------------------------------------------------------------------------
# Hostinger Cloud — install hook (called from package.json `postinstall`).
#
# Two jobs:
#   1. Install Python deps for backend/requirements.txt (best-effort — pip3
#      isn't always on PATH inside Hostinger's Node.js chroot, so we try
#      several invocations before giving up loudly).
#   2. Build the React/Vite SPA into frontend/dist (must succeed; the Node
#      server happily runs without it but the SPA won't load).
#
# We deliberately exit 0 even if the Python install can't find an
# interpreter — that way `npm install` does not fail on environments
# where Python is installed manually via SSH instead. The Node.js app
# will boot and serve a clear error from `python3` not being found
# rather than block the entire deploy.
# ----------------------------------------------------------------------------
set -u
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYREQ="$ROOT/backend/requirements.txt"

log() { printf '\n[setup.sh] %s\n' "$*"; }

# ── 1. Python deps ─────────────────────────────────────────────────────
log "1/2  Installing Python deps from backend/requirements.txt …"

PIP_OK=0
# Candidate invocations, in order of preference. The first that responds
# to `--version` wins.
CANDIDATES=(
  "python3 -m pip"
  "python3.11 -m pip"
  "python3.10 -m pip"
  "python3.9 -m pip"
  "/opt/alt/python311/bin/python3.11 -m pip"
  "/opt/alt/python310/bin/python3.10 -m pip"
  "/usr/local/bin/python3 -m pip"
  "/usr/bin/python3 -m pip"
  "pip3"
  "pip"
)

for cmd in "${CANDIDATES[@]}"; do
  if $cmd --version >/dev/null 2>&1; then
    log "   using: $cmd"
    # --user keeps installs inside the home dir (no root needed).
    # --no-warn-script-location: we don't care about $PATH for these.
    # --disable-pip-version-check: speed.
    # --prefer-binary: dodge native build tools we don't have on shared hosts.
    if $cmd install --user \
        --no-warn-script-location \
        --disable-pip-version-check \
        --prefer-binary \
        -r "$PYREQ"; then
      PIP_OK=1
      break
    else
      log "   ⚠  $cmd install failed; trying next candidate …"
    fi
  fi
done

if [ "$PIP_OK" = 0 ]; then
  log "⚠  Could not install Python deps automatically."
  log "   You will need to SSH in once and run:"
  log "       python3 -m pip install --user -r backend/requirements.txt"
  log "   (deploy will continue; Node will start but FastAPI will crash"
  log "    on the first /api request until pip install succeeds)."
fi

# ── 2. Frontend build ──────────────────────────────────────────────────
log "2/2  Building React SPA into frontend/dist …"

# ── Pre-clean to dodge npm's Rollup optional-dep bug AND Hostinger's
#    EMLINK errors on the shared ~/.npm/_cacache symlink store.
# Symptoms we are defending against, observed in actual hPanel build logs:
#   1) "Cannot find module @rollup/rollup-linux-x64-gnu" (npm/cli #4828)
#   2) "EMLINK: not permitted, unlink '~/.npm/vite/2.0.1/package/...'"
#      → npm 7+ on Hostinger can't unlink stale entries another tenant
#        wrote into the shared cacache. We bypass by pointing npm at a
#        BUILD-LOCAL cache directory under /tmp that we own outright.
log "   pre-clean (absolute paths): rm -rf frontend/node_modules frontend/package-lock.json"
rm -rf "$ROOT/frontend/node_modules"
rm -rf "$ROOT/frontend/package-lock.json"
rm -rf "$ROOT/frontend/.vite"
rm -rf "$ROOT/frontend/dist"

# Build-local npm cache: side-steps Hostinger's corrupted ~/.npm.
NPM_CACHE_DIR="${TMPDIR:-/tmp}/nadiplayer-npm-cache-$$"
mkdir -p "$NPM_CACHE_DIR"
log "   using build-local npm cache: $NPM_CACHE_DIR"
export npm_config_cache="$NPM_CACHE_DIR"

# Visibility: confirm in the build log that the wipe took effect.
log "   post-clean state of frontend/:"
ls -la "$ROOT/frontend/" 2>&1 | grep -E "node_modules|package-lock|^total" || true

cd "$ROOT/frontend" || { log "✗ frontend/ missing — skipping SPA build"; exit 1; }

# Track build success so Hostinger gets a real exit code (not silent OK).
BUILD_OK=0

# Prefer yarn if present (project shipped with yarn.lock); fall back to npm.
# NOTE: the project pins @capacitor/core@^7 with @capacitor/push-notifications@^8
# which trips npm 7+'s strict peer-dep resolver. yarn classic does not enforce
# peers strictly, so it just works; for npm we MUST pass --legacy-peer-deps
# (also pinned via frontend/.npmrc as belt-and-braces).
if command -v yarn >/dev/null 2>&1; then
  log "   using yarn"
  if yarn install --network-timeout 300000 && yarn build; then
    BUILD_OK=1
  fi
else
  log "   yarn not found — using npm with --legacy-peer-deps + isolated cache"
  # --cache pin is redundant with the env var above but explicit is better.
  if npm install \
        --cache "$NPM_CACHE_DIR" \
        --no-audit --no-fund \
        --prefer-online \
        --legacy-peer-deps; then
    # Note: we no longer need to force-install @rollup/rollup-linux-x64-gnu
    # because frontend/package.json now overrides `rollup` to
    # `@rollup/wasm-node` — pure WebAssembly, zero platform binaries,
    # works identically on Linux x64 / ARM / macOS / Windows / Hostinger.
    if npm run build; then
      BUILD_OK=1
    fi
  else
    log "   ✗ npm install failed — see error above (likely cache/permission issue)"
  fi
fi

# Verify the output Hostinger expects actually exists; fail loudly otherwise.
if [ "$BUILD_OK" = "1" ] && [ -f "$ROOT/frontend/dist/index.html" ]; then
  log "   ✓ frontend build OK — frontend/dist/index.html present"
else
  log "   ✗ frontend build FAILED — frontend/dist/index.html is missing"
  log "     (this is the real failure; the previous 'pip3' / 'rollup' lines were red herrings)"
  exit 1
fi

# ── 3. Ship the PHP backend into dist/api/ ─────────────────────────────
# Hostinger's "Static Site" deployment publishes everything under the
# build's output directory (frontend/dist) to public_html/. We can't run
# FastAPI on a static plan, but we CAN ship the PHP equivalent that
# already lives in cpanel_build_php/nadiplayer/api/ — the SPA's auth
# layer calls /api/auth/login etc. and Hostinger's Apache+PHP serves it.
PHP_API_SRC="$ROOT/cpanel_build_php/nadiplayer/api"
PHP_API_DST="$ROOT/frontend/dist/api"

if [ -d "$PHP_API_SRC" ]; then
  log "3/3  Publishing PHP backend → frontend/dist/api/"
  mkdir -p "$PHP_API_DST"
  # -a preserves perms; --delete keeps the destination in sync.
  if command -v rsync >/dev/null 2>&1; then
    rsync -a --delete "$PHP_API_SRC/" "$PHP_API_DST/"
  else
    rm -rf "$PHP_API_DST"
    cp -R "$PHP_API_SRC" "$PHP_API_DST"
  fi

  # Rewrite the .htaccess RewriteBase so the API works at /api/ instead
  # of the legacy cPanel path /nadiplayer/api/.
  if [ -f "$PHP_API_DST/.htaccess" ]; then
    sed -i.bak 's#RewriteBase /nadiplayer/api/#RewriteBase /api/#g' "$PHP_API_DST/.htaccess"
    rm -f "$PHP_API_DST/.htaccess.bak"
    log "   ✓ rewrote .htaccess RewriteBase → /api/"
  fi

  # Make sure PHP files are server-readable (644) and dirs are 755.
  find "$PHP_API_DST" -type d -exec chmod 755 {} + 2>/dev/null || true
  find "$PHP_API_DST" -type f -exec chmod 644 {} + 2>/dev/null || true
  # Lock down the secrets dir + any service-account JSON.
  if [ -d "$PHP_API_DST/secrets" ]; then
    chmod 700 "$PHP_API_DST/secrets" 2>/dev/null || true
    find "$PHP_API_DST/secrets" -type f -exec chmod 600 {} + 2>/dev/null || true
  fi

  # Sanity-check the layout we just produced.
  log "   published files:"
  ls -la "$PHP_API_DST" 2>&1 | head -20

  if [ -f "$PHP_API_DST/index.php" ] && [ -f "$PHP_API_DST/.htaccess" ]; then
    log "   ✓ /api/index.php + /api/.htaccess in place"
  else
    log "   ✗ PHP backend files missing after copy — deploy will 404 on /api/*"
    exit 1
  fi
else
  log "⚠  cpanel_build_php/nadiplayer/api/ not found — skipping PHP backend publish."
  log "   (login will fail on prmtly.com until the PHP backend is deployed.)"
fi

# Also ship the auxiliary SPA-adjacent folders the upstream cPanel build
# ships alongside the API (admin panel, device pairing portal, etc.).
for sub in admin_panel pair subscription PrivacyPolicy; do
  SRC="$ROOT/cpanel_build_php/nadiplayer/$sub"
  DST="$ROOT/frontend/dist/$sub"
  if [ -d "$SRC" ]; then
    log "   publishing $sub/ → frontend/dist/$sub/"
    rm -rf "$DST"
    cp -R "$SRC" "$DST"
    find "$DST" -type d -exec chmod 755 {} + 2>/dev/null || true
    find "$DST" -type f -exec chmod 644 {} + 2>/dev/null || true
  fi
done

log "✓ done."
exit 0
