#!/usr/bin/env bash
# rap-avatar-mv — shared helpers.
#
# Deliberately thin: the path/env/pack/ffmpeg plumbing is rhyme-factory's and is
# SOURCED, not copied (the same "reuse, do not duplicate" rule rhyme-factory
# applies to garden-days). We only override the log prefix and add the rap-side
# paths and the gate helper.
set -euo pipefail

# MAIN = the repo root whose dist/ this run executes. Derived from THIS file's own
# location (lib/ -> scripts -> rap-avatar-mv -> skills -> root), because the old
# hard-coded $HOME default silently ran the MAIN CHECKOUT's dist from a worktree:
# on 2026-08-24 a worktree whose sources carried the lip-sync exempt logic ran the
# main checkout's day-old dist, and the assembler refused every exempt window as
# fatal ("cut 0 (w00)"). The runner snapshot symlinks back into its own repo, so
# deriving from BASH_SOURCE resolves to the copy the scripts were built with.
# An explicit MAIN env always wins; the old default remains the fallback for a
# checkout layout where the derived root carries no built CLI.
if [ -z "${MAIN:-}" ]; then
  _rap_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd -P)"
  if [ -f "$_rap_root/dist/cli/vclaw.js" ]; then
    MAIN="$_rap_root"
  else
    MAIN="$HOME/Documents/GitHub/videoclaw-v3"
  fi
  unset _rap_root
fi
# Exported: the Python stages that shell out to the CLI (select_cut.py --verify-plan)
# read MAIN from the environment and otherwise default to the main checkout — so the
# verifier was judging the cut against a DIFFERENT build than the one that makes it
# (film #3 v4, 2026-09-06: the worktree's fixed planner passed, the main checkout's
# refused, and the runner reported the main checkout's refusal).
export MAIN

RAP_SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"   # skills/rap-avatar-mv
RAP_SCRIPTS="$RAP_SKILL_DIR/scripts"
RAP_REFS="$RAP_SKILL_DIR/references"

_RF_COMMON="$MAIN/skills/rhyme-factory/scripts/lib/common.sh"
[ -f "$_RF_COMMON" ] || {
  printf '\033[31m[rap:ERROR]\033[0m rhyme-factory helpers not found at %s\n' "$_RF_COMMON" >&2
  printf '  This skill reuses them (load_env / load_preset / require_ffmpeg_full / project_dir).\n' >&2
  printf '  Set MAIN to the videoclaw-v3 repo root.\n' >&2
  exit 1
}
# shellcheck disable=SC1090
source "$_RF_COMMON"

# --- our own voice ---------------------------------------------------------
log(){ printf '\033[36m[rap]\033[0m %s\n' "$*" >&2; }
warn(){ printf '\033[33m[rap:warn]\033[0m %s\n' "$*" >&2; }
die(){ printf '\033[31m[rap:ERROR]\033[0m %s\n' "$*" >&2; exit 1; }

# --- rewinding the stage state -----------------------------------------------
# `--from X` means "run X and everything after it, treat everything before it as
# done". It used to keep only the earlier stages that were MARKED — so a stage an
# interrupted run never marked (render-all, after the runner was killed mid-render on
# 2026-08-29) came back to life under `--from library` and started submitting B-roll
# again. Position decides, not the mark: every stage before X is written as done, and
# any that was not already marked is announced, because that is the trace of an
# interrupted run the operator should know about.
#   state_rewind_to <state-file> <from-stage> <stage>...
state_rewind_to(){
  local state="$1" from="$2"; shift 2
  local keep="" s seen=0
  for s in "$@"; do
    [ "$s" = "$from" ] && seen=1
    [ "$seen" = 1 ] && continue
    if ! grep -qx "$s" "$state" 2>/dev/null; then
      printf '\033[33m[rap:warn]\033[0m --from %s: marking %s done (it was unmarked — an interrupted run?)\n' "$from" "$s" >&2
    fi
    keep="$keep$s"$'\n'
  done
  [ "$seen" = 1 ] || { printf '\033[31m[rap:ERROR]\033[0m --from %s is not a stage\n' "$from" >&2; return 2; }
  printf '%s' "$keep" > "$state"
}

# --- the gate --------------------------------------------------------------
# Print what the operator must do, then EXIT 10. Doing the work and re-running
# the same command IS the approval; completed stages are skipped on re-run. This
# is the spend control: an artifact that already exists is never re-bought, so
# re-rolling something paid means deleting it on purpose.
# UNATTENDED=1: the free, reversible gates pass on the operator's standing word (New Era,
# 2026-08-31: "do what u need to have the rap video all working in the morning") and are
# written to project-audit.jsonl. Every other gate still stops: the lyrics, the song, the
# climax refusal, an authored cut, the sync bar — and publish, which is never a gate() at
# all (PUBLISH_GO). The list is the runner's own gate texts; a supervisor loop that
# re-ran past a regex of its own knew 8 of the 15 and two of its patterns matched nothing.
UNATTENDED_GATES_DEFAULT='^(confirm the two styles|verify who sings|review the per-window submit contract|judge the first take|some windows did not render|approve the cut|render the deferred cutaway|final sign-off|sign off the FILM|check the captions|review the song breakdown)'
gate(){
  if [ "${UNATTENDED:-0}" = "1" ] && printf '%s' "$1" | grep -Eq "${UNATTENDED_GATES:-$UNATTENDED_GATES_DEFAULT}"; then
    printf '\n\033[33m===== GATE auto-passed (UNATTENDED=1): %s =====\033[0m\n' "$1" >&2
    if [ -n "${P:-}" ] && [ -d "$P" ]; then
      printf '{"at":"%s","event":"gate-auto-passed","gate":"%s","by":"UNATTENDED=1 (the operator'"'"'s standing word for the free gates)"}\n' \
        "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$(printf '%s' "$1" | sed 's/"/\\"/g')" >> "$P/project-audit.jsonl"
    fi
    return 0
  fi
  printf '\n\033[33m===== GATE: %s =====\033[0m\n%s\n\nDo the above, then re-run this command to resume.\n' \
    "$1" "$2" >&2
  exit 10
}

# --- whisper readiness (sung/rapped timings) -------------------------------
require_whisper(){
  have whisper || die "whisper CLI not found.
    Fix: pip install -U openai-whisper   (use the 'small' model — best for sung timings)
    or WHISPER_ENGINE=cpp in the pack (whisper.cpp: brew install whisper-cpp + a ggml model).
    The hook window is chosen from REAL word onsets; block boundaries are never guessed."
}

# ONE EAR PER FILM. WHISPER_ENGINE=openai (default) is the openai-whisper CLI;
# WHISPER_ENGINE=cpp puts the in-tree whisper.cpp shim first on PATH (Metal; the same
# 4:33 song in 41 s instead of 75 min, film #3). The engine is recorded in
# build/whisper-engine at the map stage and a later run under a different engine
# REFUSES: two ears hear two transcripts of one song, and every later verdict would
# compare words the other ear never heard.
#   whisper_engine_setup <scripts-dir>            — PATH + presence checks
#   whisper_engine_check <build-dir> <engine>      — refuse a mid-film change
#   whisper_engine_record <build-dir> <engine>     — the map stage writes it
whisper_engine_setup(){
  case "${WHISPER_ENGINE:-openai}" in
    openai) ;;
    cpp)
      export PATH="$1/whisper-cpp:$PATH"
      have whisper-cli || die "WHISPER_ENGINE=cpp needs whisper-cli on PATH (brew install whisper-cpp)"
      local models="${WHISPER_CPP_MODELS:-$HOME/videoclaw/tools/whisper-cpp/models}"
      ls "$models"/ggml-*.bin >/dev/null 2>&1 \
        || die "WHISPER_ENGINE=cpp needs a ggml model in $models (WHISPER_CPP_MODELS overrides):
    curl -L -o $models/ggml-medium.bin https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-medium.bin"
      ;;
    *) die "WHISPER_ENGINE must be openai or cpp (got '${WHISPER_ENGINE}')" ;;
  esac
}
whisper_engine_check(){
  local rec="$1/whisper-engine"
  [ -f "$rec" ] || return 0
  local was; was="$(cat "$rec")"
  [ "$was" = "$2" ] || die "this film's transcripts were made by WHISPER_ENGINE=$was; the run asks for $2.
    One ear per film: keep WHISPER_ENGINE=$was, or start the film again from scaffold
    (delete build/) so every pass is heard by the same engine."
}
whisper_engine_record(){ printf '%s\n' "$2" > "$1/whisper-engine"; }

# --- consent (a real person's face is being animated) ----------------------
require_consent(){
  [ "${PORTRAIT_CONSENT:-}" = "yes" ] || die "PORTRAIT_CONSENT is not set to 'yes' in the pack.
    This lane animates a real human face and puts words in their mouth. The pack must
    record that the portrait is the operator's own, or that its subject has agreed.
    Add PORTRAIT_CONSENT=yes to the pack once that is true."
  # A second performer is a second real face, and needs its own consent line.
  if [ -n "${PORTRAIT_2:-}" ]; then
    [ "${PORTRAIT_CONSENT_2:-}" = "yes" ] || die "PORTRAIT_CONSENT_2 is not set to 'yes' in the pack.
    This lane animates a real human face and puts words in their mouth. The pack must
    record that the second portrait is the operator's own, or that its subject has agreed.
    Add PORTRAIT_CONSENT_2=yes to the pack once that is true."
  fi
}
