#!/bin/bash
# Checks whether an ad script fits a time slot: words, predicted seconds, words that fit, and a warning for URL or code tokens.
# Usage: bash ad-length.sh <script.txt> [words-per-minute] [slot-seconds] [--speak]
#   defaults: 150 words per minute, 30 second slot. --speak also reads the script with the macOS say command and
#   measures the audio (needs say, and ffprobe or the macOS afinfo).
set -euo pipefail
usage() { echo "usage: bash ad-length.sh <script.txt> [words-per-minute 60-300] [slot-seconds] [--speak]" >&2; exit 2; }
[ $# -ge 1 ] || usage
file=$1; wpm=${2:-150}; slot=${3:-30}; speak=${4:-}
[ -f "$file" ] || { echo "file not found: $file" >&2; exit 2; }
[[ "$wpm" =~ ^[0-9]+$ ]] && [ "$wpm" -ge 60 ] && [ "$wpm" -le 300 ] || { echo "words per minute must be a whole number from 60 to 300" >&2; exit 2; }
[[ "$slot" =~ ^[0-9]+$ ]] && [ "$slot" -ge 1 ] || { echo "slot seconds must be a whole number of 1 or more" >&2; exit 2; }
# drop Windows line breaks so they do not stick to the last word
clean=$(tr -d '\r' < "$file")
words=$(printf '%s' "$clean" | wc -w | tr -d ' ')
[ "$words" -gt 0 ] || { echo "the script has no words: $file" >&2; exit 2; }
secs=$(awk -v w="$words" -v p="$wpm" 'BEGIN{printf "%.1f", w/p*60}')
fit=$(awk -v s="$slot" -v p="$wpm" 'BEGIN{printf "%d", int(s*p/60)}')
echo "words: $words"
echo "predicted length at $wpm words a minute: $secs s"
echo "words that fit $slot s at $wpm words a minute: $fit"
if [ "$words" -le "$fit" ]; then echo "fits: $((fit - words)) words of room"; else echo "too long: $((words - fit)) words over"; fi
# a URL, a promo code or a number is one word to wc but takes longer to say
odd=$(printf '%s' "$clean" | tr -s ' \t\n' '\n\n\n' | grep -E '[A-Za-z0-9]\.[A-Za-z0-9]|[/@]|[0-9]|^[A-Z]{3,}[[:punct:]]*$' | head -5 | paste -sd' ' - || true)
[ -z "$odd" ] || echo "check these tokens (a URL, code or number counts as 1 word but is longer to say; write them as you will say them): $odd"
if [ "$speak" = "--speak" ]; then
  command -v say >/dev/null || { echo "--speak needs the macOS say command" >&2; exit 2; }
  command -v ffprobe >/dev/null || command -v afinfo >/dev/null || { echo "--speak needs ffprobe or afinfo" >&2; exit 2; }
  tmp=$(mktemp "${TMPDIR:-/tmp}/adread.XXXXXX.aiff")
  printf '%s' "$clean" | say -f - -o "$tmp"
  if command -v ffprobe >/dev/null; then m=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$tmp"); else m=$(afinfo "$tmp" | awk '/estimated duration/{print $3}'); fi
  rm -f "$tmp"
  echo "measured with the macOS voice at its default rate: $(awk -v m="$m" 'BEGIN{printf "%.1f", m}') s (one synthetic voice, not your pace)"
fi
