#!/usr/bin/env bash
# 3d-animation-short — shared helpers.
#
# Thin on purpose. The path/env/pack plumbing is rhyme-factory's and is SOURCED,
# not copied — the same reuse rule rap-avatar-mv applies. We add our own log
# prefix, this skill's paths, and the gate helper.
set -euo pipefail

: "${MAIN:=$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd -P)}"

# The Flow transport shells out to the Bun-based vclaw-cli and defaults to
# looking for it under the WORKSPACE, where it does not live — it ships in the
# repo. Set it here in the launcher rather than at any call site, so a resume
# and every child process inherit it (the lesson the rap lane learned about
# VCLAW_RUNWAY_AUDIO).
: "${VCLAW_VEO_CLI_ROOT:=$MAIN/vclaw-cli}"
export VCLAW_VEO_CLI_ROOT

ANIM_SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"   # skills/3d-animation-short
ANIM_SCRIPTS="$ANIM_SKILL_DIR/scripts"
ANIM_REFS="$ANIM_SKILL_DIR/references"

_RF_COMMON="$MAIN/skills/rhyme-factory/scripts/lib/common.sh"
[ -f "$_RF_COMMON" ] || {
  printf '\033[31m[3d:ERROR]\033[0m rhyme-factory helpers not found at %s\n' "$_RF_COMMON" >&2
  printf '  This skill reuses them (load_env / load_preset / 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[3d]\033[0m %s\n' "$*" >&2; }
warn(){ printf '\033[33m[3d:warn]\033[0m %s\n' "$*" >&2; }
die(){ printf '\033[31m[3d:ERROR]\033[0m %s\n' "$*" >&2; exit 1; }

# --- 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 also the spend control: an artifact that already exists is never
# re-bought, so re-rolling something paid means deleting it on purpose.
gate(){
  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
}

# --- vclaw ------------------------------------------------------------------
vclaw(){ node "$MAIN/dist/cli/vclaw.js" "$@"; }

# --- one film, one route (and the one the PACK asked for) -------------------
# The plan falls back down a preference list when a route is unavailable, and
# records WHY in its rationale — but nothing refuses. A single missing
# credential silently moved a film from Flow to Seedance mid-production: the
# pack said veo-useapi, project.json still said veo-useapi, and every clip went
# to a different provider. Nothing was charged that time because the fallback
# route 403'd. On a paid route it would have bought the wrong lane in silence,
# and on a working one it would have shipped a film with a visible style seam.
#
# So: assert the route the plan will ACTUALLY use is the route asked for.
assert_route_locked(){
  local plan resolved
  plan="$(vclaw video execution-plan --project "$SLUG" --root "$VCLAW_WORKSPACE" 2>/dev/null)" || {
    warn "could not build an execution plan to check the route"
    return 1
  }
  resolved="$(printf '%s' "$plan" | python3 -c "
import json, sys
try:
    plan = json.load(sys.stdin).get('plan') or {}
except json.JSONDecodeError:
    raise SystemExit(0)
print(plan.get('recommendedRouteId') or '')
for line in plan.get('rationale') or []:
    print(f'  {line}', file=sys.stderr)
")"
  [ "$resolved" = "$ROUTE" ] && return 0
  warn "the pack asks for '$ROUTE' but the plan resolves '${resolved:-<none>}' (rationale above)"
  return 1
}

# --- outcome, not exit code -------------------------------------------------
# `vclaw video execute` returns 0 even when it BLOCKS — it records
# status:"blocked" plus the reason in the execution report and exits success.
# So a missing artifact reads exactly like a completed submit unless the report
# itself is read. Working-discipline rule 7 in one function.
assert_submitted(){
  local report="$P/artifacts/execution-report.json"
  [ -f "$report" ] || { warn "no execution report at $report"; return 1; }
  python3 - "$report" <<'PY'
import json, sys
report = json.load(open(sys.argv[1], encoding="utf-8"))
status = report.get("status")
blockers = report.get("blockers") or []
if blockers or status == "blocked":
    print(f"  execute reported status={status!r} and did NOT submit:", file=sys.stderr)
    for blocker in blockers:
        print(f"    BLOCKER: {blocker}", file=sys.stderr)
    raise SystemExit(1)
print(f"  execute status={status!r}", file=sys.stderr)
PY
}

# The stronger check, and the one that actually matters: is there a CLIP on disk
# for every shot? `assert_submitted` reads a report, and a report can say
# live-submitted with no blockers while the driver reported individual scenes
# `skipped` (an orphaned selection) or `failed` (a job still in flight). That is
# how render-all got marked complete with two of three clips missing, leaving
# assembly to discover it. A report is a claim; the clips are the outcome.
# Routes render in their OWN increments and ignore the table's per-shot seconds:
# Flow returned 8s for shots planned at 6, 7 and 7. Nothing reconciled the two,
# and `assemble --from-clips` concatenates WHOLE clips — `clipMaxSeconds` is one
# global cap, and nothing in that path reads scene.durationSeconds. So a 20s
# plan would have shipped as a 24s film with totalDurationSeconds:20 recorded in
# the artifact, and no gate would have said a word.
assert_planned_duration(){
  python3 - "$TABLE" "$P" <<'PY'
import json, os, subprocess, sys
table_path, project = sys.argv[1], sys.argv[2]
shots = json.load(open(table_path, encoding="utf-8"))["shots"]
rows, planned_total, actual_total = [], 0.0, 0.0
for i, shot in enumerate(shots):
    clip = os.path.join(project, "outputs", f"scene-{i}.mp4")
    planned = float(shot.get("durationSeconds") or 0)
    planned_total += planned
    if not os.path.isfile(clip):
        continue
    out = subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries", "format=duration",
         "-of", "default=nk=1:nw=1", clip],
        capture_output=True, text=True, check=False).stdout.strip()
    actual = float(out) if out else 0.0
    actual_total += actual
    if abs(actual - planned) > 0.25:
        rows.append(f"  {shot.get('id')}: planned {planned:g}s, rendered {actual:g}s")
if rows:
    print(f"  the render does not match the plan ({planned_total:g}s planned, "
          f"{actual_total:g}s rendered):", file=sys.stderr)
    for row in rows:
        print(row, file=sys.stderr)
    raise SystemExit(1)
PY
}

assert_clips_present(){
  local expected="$1" missing=()
  local i=0
  while [ "$i" -lt "$expected" ]; do
    [ -f "$P/outputs/scene-$i.mp4" ] || missing+=("scene-$i")
    i=$((i + 1))
  done
  [ ${#missing[@]} -eq 0 ] && return 0
  warn "no clip on disk for: ${missing[*]}"
  return 1
}

# --- route readiness --------------------------------------------------------
# One film, one route: mixing routes inside a film leaves a visible style seam.
# The two lanes this engine is driven on differ in what they need up front, and
# neither failure is obvious at render time.
require_route(){
  case "${ROUTE:-veo-useapi}" in
    veo-useapi)
      [ -n "${USEAPI_API_TOKEN:-}" ] || die "veo-useapi needs USEAPI_API_TOKEN in $MAIN/.env.local.
    Flow locks identity on a REGISTERED Flow Character, so the cast must also be
    registered out of band (vclaw video flow-register-characters) before a render.
    show-preflight enforces that — it never fabricates a registration."
      ;;
    runway-useapi)
      [ -n "${USEAPI_API_TOKEN:-}" ] || die "runway-useapi needs USEAPI_API_TOKEN in $MAIN/.env.local."
      log "route: runway-useapi explore — 0 credits, but it admits 2-3 jobs at a time"
      log "       and can queue for a couple of hours. Plan the wait, not the spend."
      ;;
    dreamina-useapi|seedance-direct)
      log "route: ${ROUTE} is a PAID lane. Every render costs credits."
      ;;
    *) die "unknown ROUTE '${ROUTE}'. See references/route-matrix.md." ;;
  esac
}
