#!/bin/sh
set -eu

# Anthem — Submit Caption Corrections
#
# Double-click this after you have fixed captions in Premiere. It asks for the
# XML you exported from the caption nest and sends it to Anthem so future
# captions learn from your edits. It never touches your project.
#
# The editor never needs a job id: the exported sequence is still named
# "Anthem Captions <run>-<id>", and the server uses that to match the run.
#
# The engine address is baked at build time or overridden with ANTHEM_ENGINE_URL.

ENGINE_URL="${ANTHEM_ENGINE_URL:-https://engine.vihaga.dev}"

say() {
  /usr/bin/osascript -e "display dialog $(printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g; s/^/"/; s/$/"/') buttons {\"OK\"} default button \"OK\" with title \"Anthem\"" >/dev/null 2>&1 || true
}

fail() {
  say "$1"
  exit 2
}

case "$ENGINE_URL" in
  https://*) ;;
  *) fail "This helper was not finalized with an engine address. Ask your Anthem contact for an updated copy." ;;
esac

# Native file picker beats asking an editor to find a path in Terminal.
XML=$(/usr/bin/osascript <<'APPLESCRIPT' 2>/dev/null || true
set theFile to choose file with prompt "Choose the caption XML you exported from Premiere (File > Export > Final Cut Pro XML)" of type {"xml", "public.xml"} default location (path to desktop folder)
POSIX path of theFile
APPLESCRIPT
)

[ -n "$XML" ] || exit 0          # editor pressed Cancel
[ -f "$XML" ] || fail "That file could not be read. Try exporting the caption nest again."

# Reject the obvious mistake early, with the fix in the message, rather than
# making the editor wait for a round trip to find out.
if ! /usr/bin/grep -q "Anthem Captions" "$XML" 2>/dev/null; then
  fail "That file has no Anthem caption sequence in it.

In Premiere, select the ANTHEM | NATIVE CAPTIONS nest, then choose
File > Export > Final Cut Pro XML, and pick that file here."
fi

RESPONSE=$(/usr/bin/curl --fail --silent --show-error --max-time 120 \
  --proto '=https' --tlsv1.2 \
  -X POST --data-binary "@$XML" \
  -H "Content-Type: application/xml" \
  "$ENGINE_URL/v1/corpus/edited" 2>&1) || {
    say "Anthem could not send your corrections.

$RESPONSE

Check your internet connection and try again. Nothing on your Mac was changed."
    exit 2
  }

say "Thank you — your caption corrections were sent to Anthem.

Future captions will be improved using these edits. Nothing in your Premiere project was changed."
