#!/usr/bin/env bash
# Low-memory Basic page -> Paragraphs conversion for a server with a tight
# per-account memory cap. Runs the reviewed conversion in small groups of
# pages, each group in its own short PHP process, in the reviewed batch order.
#
# Usage (from the project root, after the dry run matched expectations):
#   scripts/paragraphs-rollout/convert-pages.sh <policy-dir> <dry-run-report-dir> [group-size]
#   group-size defaults to 3 pages per PHP process; use 1 if a group runs out of memory.
#
# Environment:
#   PHP_MEMORY   PHP memory_limit per process (default 160M; must stay below the
#                account's per-process data limit, see `ulimit -d`)
#   AS_UID       active administrator uid for revisions (default 1)
#   SKIP_PAGES   comma-separated node IDs to leave on their legacy rendering in
#                this run, for example pages too large for the memory limit
#                (see the module README). Only IDs present in expected.json.
#
# Behaviour:
# - Applies only pages listed in <dry-run-report-dir>/expected.json, batch by
#   batch (a_consistent, b_markup_only, c_aligned, d_german_or_single,
#   f_special), <group-size> pages per PHP process.
# - Skips the extra targeted search indexing call (--no-reindex). The
#   kaindl_site index still indexes saved pages directly; check
#   `search-api:status kaindl_site` afterwards as described in the module README.
# - Stops at the first failing group. Other pages of that group may already be
#   applied. A page that reports stale_plan because its images are now shared
#   media is handled per the README "Shared media" step; then rerun this
#   script with the same arguments: already converted pages report noop.
# - Writes every group's JSON result to a new per-run folder
#   <dry-run-report-dir>/apply-log-<timestamp>-<pid>/, so a rerun keeps earlier logs.
set -euo pipefail

policy="${1:?policy directory required}"
report="${2:?dry-run report directory required}"
group="${3:-3}"
mem="${PHP_MEMORY:-160M}"
uid="${AS_UID:-1}"
drush=(php -d "memory_limit=$mem" vendor/drush/drush/drush.php)

[ -f composer.json ] && [ -f vendor/drush/drush/drush.php ] || { echo "Run from the project root." >&2; exit 2; }
[ -d "$policy/pages" ] || { echo "Policy directory has no pages/." >&2; exit 2; }
[ -f "$report/expected.json" ] || { echo "No expected.json in $report." >&2; exit 2; }
case "$group" in ''|*[!0-9]*) echo "Group size must be a number." >&2; exit 2;; esac

[ "$group" -ge 1 ] || { echo "Group size must be at least 1." >&2; exit 2; }

policy="$(cd "$policy" && pwd)"
report="$(cd "$report" && pwd)"

# Validate expected.json once, before any write, and list "batch nid" pairs.
plan="$(php -r '
  $e = json_decode((string) file_get_contents($argv[1]), TRUE, 512, JSON_THROW_ON_ERROR);
  if (!is_array($e) || $e === []) { fwrite(STDERR, "expected.json is empty.\n"); exit(1); }
  foreach ($e as $nid => $row) {
    if (!ctype_digit((string) $nid) || !isset($row["batch"], $row["plan_hash"], $row["revision"])) {
      fwrite(STDERR, "expected.json has an invalid entry.\n"); exit(1);
    }
    echo $row["batch"], " ", $nid, PHP_EOL;
  }
' "$report/expected.json")" || { echo "STOP: expected.json could not be read." >&2; exit 2; }
batches="a_consistent b_markup_only c_aligned d_german_or_single f_special"
total="$(printf '%s\n' "$plan" | grep -c .)"
known="$(printf '%s\n' "$plan" | awk -v list="$batches" 'BEGIN {n = split(list, a, " "); for (i = 1; i <= n; i++) ok[a[i]] = 1} ($1 in ok) {c++} END {print c + 0}')"
if [ "$known" -ne "$total" ]; then
  echo "STOP: $total pages expected but only $known belong to the known batches. Nothing applied." >&2
  exit 2
fi
skip="${SKIP_PAGES:-}"
case "$skip" in ''|[0-9]*) ;; *) echo "SKIP_PAGES must be comma-separated node IDs." >&2; exit 2;; esac
if [ -n "$skip" ]; then
  [[ "$skip" =~ ^[0-9]+(,[0-9]+)*$ ]] || { echo "SKIP_PAGES must be comma-separated node IDs." >&2; exit 2; }
  for nid in ${skip//,/ }; do
    printf '%s\n' "$plan" | awk -v n="$nid" '$2 == n {f=1} END {exit !f}' \
      || { echo "SKIP_PAGES: $nid is not in expected.json. Nothing applied." >&2; exit 2; }
  done
  plan="$(printf '%s\n' "$plan" | awk -v s=",$skip," 'index(s, "," $2 ",") == 0')"
  echo "Skipping (left on legacy rendering): $skip"
fi
echo "expected.json: $total pages, $(printf '%s\n' "$plan" | grep -c .) to apply"

log="$report/apply-log-$(date +%Y%m%d-%H%M%S)-$$"
mkdir "$log"

for batch in $batches; do
  mapfile -t nids < <(printf '%s\n' "$plan" | awk -v b="$batch" '$1 == b {print $2}')
  [ "${#nids[@]}" -gt 0 ] || continue
  echo "== $batch: ${#nids[@]} pages"
  for ((i = 0; i < ${#nids[@]}; i += group)); do
    pages="$(IFS=,; echo "${nids[*]:i:group}")"
    out="$log/$batch-$(printf '%03d' "$i").json"
    if ! "${drush[@]}" kaindl-components:migrate-pages \
        --policy-dir="$policy" --pages="$pages" --apply \
        --expected="$report/expected.json" --as-uid="$uid" --no-reindex > "$out"; then
      # The process can end abnormally after the pages were committed (for
      # example during search indexing at shutdown). Continue only when the
      # complete result lists every page of the group as migrated or noop.
      if php -r '
          $t = file_get_contents($argv[1]); $i = strpos($t, "[");
          $r = $i === FALSE ? NULL : json_decode(substr($t, $i), TRUE);
          if (!is_array($r)) { exit(1); }
          $ok = [];
          foreach ($r as $row) {
            if (in_array($row["status"] ?? "", ["migrated", "noop"], TRUE)) { $ok[] = (string) ($row["nid"] ?? ""); }
          }
          $want = explode(",", $argv[2]);
          exit(array_diff($want, $ok) === [] ? 0 : 1);
        ' "$out" "$pages"; then
        echo "  $pages converted, but the PHP process ended abnormally afterwards (see $out). Continuing; check search-api:status at the end." >&2
        abnormal="${abnormal:+$abnormal,}$pages"
        continue
      fi
      echo "STOP: group $pages failed. See $out" >&2
      php -r '
        $t = file_get_contents($argv[1]); $i = strpos($t, "[");
        foreach (json_decode(substr($t, $i ?: 0), TRUE) ?: [] as $r) {
          if (($r["status"] ?? "") === "failed") { echo "  ", $r["nid"], ": ", $r["code"], " - ", $r["message"], PHP_EOL; }
        }' "$out" || true
      exit 1
    fi
    php -r '
      $t = file_get_contents($argv[1]); $i = strpos($t, "[");
      $c = array_count_values(array_column(json_decode(substr($t, $i ?: 0), TRUE) ?: [], "status"));
      echo "  ", $argv[2], " ", json_encode($c), PHP_EOL;' "$out" "$pages"
  done
done
echo "Done: $(printf '%s\n' "$plan" | grep -c .) of $total pages processed${skip:+ (skipped: $skip)}. Logs: $log"
if [ -n "${abnormal:-}" ]; then
  echo "Converted, but the PHP process ended abnormally afterwards for pages: $abnormal" >&2
fi
echo "Next: idempotence dry run, search-api:status kaindl_site, cache rebuild."
