#!/usr/bin/env bash
# brand-explainer — shared helpers. `source` this from every brand-explainer script.
# No hardcoded repo path: everything resolves from env with sane defaults.
set -euo pipefail

# --- paths (all env-overridable) -------------------------------------------
: "${VCLAW_WORKSPACE:=$HOME/videoclaw}"                 # where projects/<slug>/ live
: "${MAIN:=$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd -P)}"        # repo root (.env, dist, skills)
: "${VCLAW_PACKS:=$VCLAW_WORKSPACE/packs}"              # brand packs (schema: packs/README.md)

BE_SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"   # skills/brand-explainer
BE_SCRIPTS="$BE_SKILL_DIR/scripts"
QC_SPACING="$MAIN/skills/mograph/scripts/deterministic/qc_spacing.py"

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

# --- repo creds (ELEVENLABS_API_KEY, SUNO/…) --------------------------------
load_env(){
  local f
  for f in "$MAIN/.env" "$MAIN/.env.local"; do
    # shellcheck disable=SC1090
    [ -f "$f" ] && { set -a; source "$f"; set +a; }
  done
  return 0   # never let a missing .env (last test false) kill callers under set -e
}

# --- pack sourcing (accepts name | path) -----------------------------------
# Resolves a BRAND pack. Exports BRAND_PACK for the python workers.
load_pack(){
  local name="$1" p="$1"
  [ -f "$p" ] || p="$VCLAW_PACKS/$name.brand"
  [ -f "$p" ] || die "brand pack '$name' not found (looked in $VCLAW_PACKS)"
  # shellcheck disable=SC1090
  set -a; source "$p"; set +a
  export BRAND_PACK="$p"
  log "loaded pack: $p"
}

# --- per-video overrides (source AFTER the pack so the video wins) ----------
load_video_env(){
  local proj="$1"
  # shellcheck disable=SC1090
  [ -f "$proj/video.env" ] && { set -a; source "$proj/video.env"; set +a; log "loaded video overrides: $proj/video.env"; }
  return 0
}

# --- small helpers ---------------------------------------------------------
project_dir(){ echo "$VCLAW_WORKSPACE/projects/$1"; }
dur(){ ffprobe -v error -show_entries format=duration -of default=nk=1:nw=1 "$1"; }
have(){ command -v "$1" >/dev/null 2>&1; }
