#!/usr/bin/env bash
#
# build.sh: the images for "Dark Night of the Soul"
#
# St. John of the Cross wrote eight five-line stanzas about a soul that slips out of her
# quiet house at night, guided only by the ember in her chest, toward the Beloved who waits.
# This script retells every stanza as dark-fantasy anime with rose.py and FLUX.2 on Replicate:
# four shots per stanza, plus a fifth for stanzas 5-8, where the two lovers meet (36 candidates).
# The published post keeps the best three per stanza (24); the shots listed in EXCLUDED below
# were cut after review, and a normal run does not regenerate them.
#
#   Poem:   https://en.wikipedia.org/wiki/Dark_Night_of_the_Soul
#   Text:   English translation by E. Allison Peers
#   Style:  Bloodborne, Resident Evil, Anime, Devil May Cry
#
# Usage:  ./build.sh [options]       (REPLICATE_API_TOKEN must be set)
#   -s, --stanza N[,N...]   only these stanzas (1-8)
#   -k, --shot N[,N...]     only these shots (1-5) of the chosen stanzas; always regenerates them
#                           with the seed they had in a full run, so a redo stays reproducible
#   -m, --model REF         Replicate model         (default black-forest-labs/flux-2-pro)
#   -a, --aspect RATIO      aspect ratio            (default 3:2)
#   -r, --resolution RES    e.g. "2 MP"             (default: the model's)
#   -S, --seed N            base seed               (default 1572; reproducible)
#   -j, --jobs N            parallel predictions    (default 4)
#   -f, --force             regenerate stanzas whose images already exist
#   -n, --dry-run           print the prompts and payloads, generate nothing
#   -h, --help
#
# Every stanza gets four shots (establishing, action, portrait, symbol); stanzas 5-8, where the
# heroine and the Beloved are together, get a fifth (a two-shot). All share one style
# block and one heroine, so the set stays visually consistent. Images land next to this file
# as dark-night-<stanza>-<shot>.jpg. Existing stanzas are skipped, so an interrupted run
# resumes where it stopped. When all kept images exist, the post's `draft` flag is cleared.

set -Eeuo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROSE="${ROSE_PY:-$HERE/../../../rose.py}"

MODEL="black-forest-labs/flux-2-pro"
ASPECT="3:2"
RESOLUTION=""
SEED=1572
JOBS=4
FORMAT="jpg"
QUALITY=95
FORCE=0
DRY=0
ONLY=""
SHOT_ONLY=""

# Shots cut after review, as <stanza>-<shot>. A full run skips them; --shot can still redo one.
EXCLUDED=(01-02 02-01 03-04 04-02 05-03 05-05 06-02 06-05 07-04 07-05 08-03 08-05)

# ---------------------------------------------------------------------------------------
# The look: one style block and one heroine, reused in every prompt
# ---------------------------------------------------------------------------------------
TITLE="Dark Night of the Soul"

STYLE="Dark fantasy anime key visual, cel-shaded characters over painterly gothic backgrounds. \
Bloodborne Victorian gothic horror and cosmic dread, Resident Evil survival-horror lighting \
with desaturated shadows, Devil May Cry stylish demon-hunter flair. Deep blacks, volumetric \
fog, cold moonlit blue against a single ember-red accent, razor-sharp linework, cinematic \
composition, highly detailed. No text, no letters, no watermark, no logo."

HEROINE="The heroine is a young woman with short silver-white hair and pale skin, wearing a \
tattered black-and-crimson Victorian coat with a high collar and fingerless gloves, an ember \
glowing softly in her chest."

BELOVED="The Beloved is a tall, calm, pale figure in a long black coat with small curved \
horns and quiet scarlet eyes, a gentle presence rather than a threat."

# Four shots per stanza; @MOTIF@ in the last one is replaced by the stanza's symbol
SHOT[1]="Wide cinematic establishing shot, the small figure dwarfed by the architecture."
SHOT[2]="Dramatic low-angle action pose, dynamic diagonal composition, flowing coat."
SHOT[3]="Intimate close-up portrait of her face and eyes lit by the ember glow, detailed anime face."
SHOT[4]="Extreme close-up still life of @MOTIF@, shallow depth of field, moody rim light."
SHOT[5]="Cinematic side-view two-shot of the heroine and the Beloved together, shallow depth of field, \
rim light and painterly bokeh, full-frame single illustration."

# ---------------------------------------------------------------------------------------
# The poem, stanza by stanza (E. Allison Peers), each with its scene and symbol
# ---------------------------------------------------------------------------------------

# On a dark night, / Kindled in love with yearnings / —oh, happy chance!— /
# I went forth without being observed, / My house being now at rest.
SCENE[1]="At midnight she slips out through the iron gate of a silent gothic manor into the fog of a \
Yharnam-like cobblestone street, every window of the house behind her dark and sleeping. $HEROINE"
MOTIF[1]="a rusted gate latch, a drift of black feathers and a faint red glow"

# In darkness and secure, / By the secret ladder, disguised / —oh, happy chance!— /
# In darkness and in concealment, / My house being now at rest.
SCENE[2]="Disguised in a ragged hooded cloak, she climbs down a hidden rusted iron ladder inside a \
cathedral wall, chains and gargoyles all around her, the vault below swallowed by darkness. $HEROINE"
MOTIF[2]="a gloved hand gripping a rusted iron ladder rung over a black abyss"

# In the happy night, / In secret, when none saw me, / Nor I beheld aught, /
# Without light or guide, / save that which burned in my heart.
SCENE[3]="She walks without lantern through a ruined labyrinth of streets where faceless statues \
and sleeping beasts crouch in the shadows, the only light the ember burning through her chest. $HEROINE"
MOTIF[3]="a glowing ember cupped in two gloved hands, light spilling between the fingers, one \
full-frame macro illustration with no inset panel, border or collage"

# This light guided me / More surely than the light of noonday / To the place where he
# (well I knew who!) / was awaiting me— / A place where none appeared.
SCENE[4]="Led by her ember, she reaches a vast empty cathedral under a moonless sky; at the far end \
of the nave a tall silhouette waits by a doorway where light seeps through the cracks. $HEROINE $BELOVED"
MOTIF[4]="a heavy gothic door with warm red light pouring through its keyhole and seams"

# Oh, night that guided me, / Oh, night more lovely than the dawn, / Oh, night that joined /
# Beloved with lover, / Lover transformed in the Beloved!
SCENE[5]="Beneath a blood-red moon and a spiral of cosmic stars, the heroine and the Beloved stand \
face to face as their two silhouettes merge into one figure of light, a Bloodborne-style cosmic sky \
above a still black lake. $HEROINE $BELOVED"
MOTIF[5]="a blood-red moon ringed by a spiral of stars reflected in black water"

# Upon my flowery breast, / Kept wholly for himself alone, / There he stayed sleeping, /
# and I caressed him, / And the fanning of the cedars made a breeze.
SCENE[6]="In an overgrown moonlit crypt garden of red roses and white lilies under tall cedars, the \
Beloved sleeps with his head on her lap while she gently strokes his hair, a calm, tender, chaste \
scene. $HEROINE $BELOVED"
MOTIF[6]="red roses and white lilies growing through cracked stone, cedar needles in the air"

# The breeze blew from the turret / As I parted his locks; / With his gentle hand /
# he wounded my neck / And caused all my senses to be suspended.
SCENE[7]="On a windswept castle turret at night the heroine parts the Beloved's long hair, his gloved \
hand resting gently at her neck, her coat and petals frozen mid-air as time itself is suspended. \
$HEROINE $BELOVED"
MOTIF[7]="a black-gloved hand and a single crimson petal frozen in mid-air"

# I remained, lost in oblivion; / My face I reclined on the Beloved. / All ceased and I
# abandoned myself, / Leaving my cares / forgotten among the lilies.
SCENE[8]="At the first grey of dawn she rests her face against the Beloved's chest among white lilies, \
her cares dissolving into black butterflies and drifting ash, utterly at peace. $HEROINE $BELOVED"
MOTIF[8]="white lilies with black butterflies rising from them in the pale dawn light"

STANZAS=8
shots_for() { if (($1 >= 5)); then echo 5; else echo 4; fi; } # stanzas 5-8 add a two-shot

# ---------------------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------------------
if [[ -t 2 ]]; then
  B=$'\033[1m' D=$'\033[2m' R=$'\033[31m' G=$'\033[32m' Y=$'\033[33m' C=$'\033[36m' Z=$'\033[0m'
else
  B="" D="" R="" G="" Y="" C="" Z=""
fi
say() { printf '%s\n' "$*" >&2; }
die() { say "${R}error:${Z} $*"; exit 2; }
usage() { sed -n '/^# Usage:/,/^#   -h/p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; }

stanza_prompt() { # stanza shot -> one-line prompt
  local s=$1 k=$2 shot=${SHOT[$2]}
  shot=${shot//@MOTIF@/${MOTIF[$s]}}
  printf '"%s", verse %d of %d. %s %s %s' "$TITLE" "$s" "$STANZAS" "$STYLE" "${SCENE[$s]}" "$shot" |
    tr -s '[:space:]' ' '
}

run_rose() { # prompts_file seed out_dir
  local args=(replicate "$MODEL" --prompts-file "$1" --jobs "$JOBS" --seed "$2"
    --aspect-ratio "$ASPECT" --output-format "$FORMAT" --output-quality "$QUALITY"
    --output-dir "$3" --no-meta)
  [[ -n "$RESOLUTION" ]] && args+=(--resolution "$RESOLUTION")
  ((DRY)) && args+=(--dry-run)
  python3 "$ROSE" "${args[@]}"
}

excluded() { # stanza shot -> 0 when the shot was cut
  local key
  printf -v key '0%d-0%d' "$1" "$2"
  [[ " ${EXCLUDED[*]} " == *" $key "* ]]
}

stanza_done() { # stanza -> 0 when all kept shots exist
  local k
  for ((k = 1; k <= $(shots_for "$1"); k++)); do
    ! excluded "$1" "$k" || continue
    compgen -G "$HERE/dark-night-0$1-0$k.*" >/dev/null || return 1
  done
}

# ---------------------------------------------------------------------------------------
# Options
# ---------------------------------------------------------------------------------------
while (($#)); do
  case "$1" in
    -s | --stanza) ONLY="${2:?--stanza needs a value}"; shift 2 ;;
    -k | --shot) SHOT_ONLY="${2:?--shot needs a value}"; shift 2 ;;
    -m | --model) MODEL="${2:?--model needs a value}"; shift 2 ;;
    -a | --aspect) ASPECT="${2:?--aspect needs a value}"; shift 2 ;;
    -r | --resolution) RESOLUTION="${2:?--resolution needs a value}"; shift 2 ;;
    -S | --seed) SEED="${2:?--seed needs a value}"; shift 2 ;;
    -j | --jobs) JOBS="${2:?--jobs needs a value}"; shift 2 ;;
    -f | --force) FORCE=1; shift ;;
    -n | --dry-run) DRY=1; shift ;;
    -h | --help) usage; exit 0 ;;
    *) die "unknown option: $1 (try --help)" ;;
  esac
done

[[ -f "$ROSE" ]] || die "rose.py not found at $ROSE (set ROSE_PY)"
command -v python3 >/dev/null || die "python3 is required"
[[ -n "${REPLICATE_API_TOKEN:-}" ]] || die "REPLICATE_API_TOKEN is not set"

if [[ -n "$ONLY" ]]; then
  IFS=',' read -r -a WANT <<<"$ONLY"
  for n in "${WANT[@]}"; do
    [[ "$n" =~ ^[1-8]$ ]] || die "stanza must be 1-8, got '$n'"
  done
else
  WANT=(1 2 3 4 5 6 7 8)
fi
if [[ -n "$SHOT_ONLY" ]]; then
  IFS=',' read -r -a SHOT_WANT <<<"$SHOT_ONLY"
  for n in "${SHOT_WANT[@]}"; do
    [[ "$n" =~ ^[1-5]$ ]] || die "shot must be 1-5, got '$n'"
  done
fi

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

# ---------------------------------------------------------------------------------------
# Generate
# ---------------------------------------------------------------------------------------
say "${B}${TITLE}${Z}  ${D}${MODEL} · ${ASPECT} · seed ${SEED} · ${#WANT[@]} stanza(s), 4-5 shots each${Z}"

failed=0
for s in "${WANT[@]}"; do
  if [[ -n "$SHOT_ONLY" ]]; then
    # Redo single shots, each with the seed it has in a full run
    for k in "${SHOT_WANT[@]}"; do
      if ((k > $(shots_for "$s"))); then
        say "${Y}stanza $s has no shot $k, skipping${Z}"
        continue
      fi
      say ""
      say "${C}${B}stanza $s/$STANZAS, shot $k/$(shots_for "$s")${Z}"
      one="$TMP/stanza-$s-$k.txt"
      stanza_prompt "$s" "$k" >"$one"
      printf '\n' >>"$one"
      if ! run_rose "$one" $((SEED + (s - 1) * 10 + k - 1)) "$TMP/out-$s-$k"; then
        say "${Y}shot $k of stanza $s failed${Z}"
        failed=1
      fi
      ((DRY)) && continue
      src="$(find "$TMP/out-$s-$k" -maxdepth 1 -type f -name '*-01.*' 2>/dev/null | head -n1 || true)"
      [[ -n "$src" ]] || continue
      rm -f "$HERE"/dark-night-0"$s"-0"$k".*
      mv -f "$src" "$HERE/dark-night-0$s-0$k.${src##*.}"
      say "${G}saved${Z} dark-night-0$s-0$k.${src##*.}"
    done
    continue
  fi

  if ((!FORCE && !DRY)) && stanza_done "$s"; then
    say "${D}stanza $s/$STANZAS already done, skipping (use --force)${Z}"
    continue
  fi
  say ""
  say "${C}${B}stanza $s/$STANZAS${Z}"

  prompts="$TMP/stanza-$s.txt"
  : >"$prompts"
  for ((k = 1; k <= $(shots_for "$s"); k++)); do
    stanza_prompt "$s" "$k" >>"$prompts"
    printf '\n' >>"$prompts"
  done

  if ! run_rose "$prompts" $((SEED + (s - 1) * 10)) "$TMP/out-$s"; then
    say "${Y}stanza $s: some images failed, rerun to retry${Z}"
    failed=1
  fi
  ((DRY)) && continue

  # rose.py numbers results <model>-<timestamp>-01..04; name them dark-night-<stanza>-<shot>
  for ((k = 1; k <= $(shots_for "$s"); k++)); do
    ! excluded "$s" "$k" || continue
    src="$(find "$TMP/out-$s" -maxdepth 1 -type f -name "*-0$k.*" 2>/dev/null | head -n1 || true)"
    [[ -n "$src" ]] || continue
    mv -f "$src" "$HERE/dark-night-0$s-0$k.${src##*.}"
    say "${G}saved${Z} dark-night-0$s-0$k.${src##*.}"
  done
done

# ---------------------------------------------------------------------------------------
# Publish the post once everything exists
# ---------------------------------------------------------------------------------------
if ((!DRY)); then
  complete=1
  for ((s = 1; s <= STANZAS; s++)); do stanza_done "$s" || complete=0; done
  if ((complete)); then
    if grep -q '^draft: true$' "$HERE/index.md"; then
      sed -i 's/^draft: true$/draft: false/' "$HERE/index.md"
      say ""
      total=0
      for ((s = 1; s <= STANZAS; s++)); do
        for ((k = 1; k <= $(shots_for "$s"); k++)); do excluded "$s" "$k" || total=$((total + 1)); done
      done
      say "${G}All $total images exist: draft flag cleared in index.md.${Z}"
    fi
  else
    say ""
    say "${Y}Not every stanza has its images yet, so the post stays a draft.${Z}"
  fi
fi

exit "$failed"
