#!/usr/bin/env zsh
# export-vectors.zsh — downloads auto-detected vector SVGs from Figma.
# Reads _sologen/json/auto-vectors.json (produced by generate-asset-names.mjs),
# calls the Figma images API, and writes SVGs to the campaign's images/ directory.
# No-op when auto-vectors.json is absent or empty.
set -euo pipefail

campaign="${1:-}"
desktop_url="${2:-${DESKTOP_URL:-}}"
mobile_url="${3:-${MOBILE_URL:-}}"

if [[ -z "$campaign" ]]; then
  echo "usage: scripts/export-vectors.zsh <campaign> [desktop_url] [mobile_url]"
  exit 1
fi

if [[ -z "${FIGMA_TOKEN:-}" ]]; then
  echo "ERROR Missing FIGMA_TOKEN"
  exit 1
fi

campDir="campaigns/content/$campaign/awareness"
jsonDir="$campDir/_sologen/json"
autoVectorsJson="$jsonDir/auto-vectors.json"
assetNamesSh="$jsonDir/asset-names.sh"
outDir="$campDir/images"

# No auto-vectors file or empty nodeIds = nothing to do
if [[ ! -s "$autoVectorsJson" ]]; then exit 0; fi

nodeIds="$(node -e '
const j=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"));
const ids=Array.isArray(j.nodeIds)?j.nodeIds:[];
process.stdout.write(ids.join(","));
' "$autoVectorsJson" 2>/dev/null)"

if [[ -z "$nodeIds" ]]; then exit 0; fi

# Extract filekey from URL (same pattern as export-exportables.zsh)
extract_file_key(){ printf '%s' "$1" | sed -En 's#^(https?://|figma://)[^/]+/(file|design|proto)/([A-Za-z0-9_-]+).*#\3#p' | head -n1; }
filekey=""
if [[ -n "$desktop_url" ]]; then filekey="$(extract_file_key "$desktop_url")"; fi
if [[ -z "$filekey" && -n "$mobile_url" ]]; then filekey="$(extract_file_key "$mobile_url")"; fi
if [[ -z "$filekey" ]]; then
  # Fall back to fileKey stored in preflight.json
  preflight="$campDir/_sologen/json/preflight.json"
  [[ -s "$preflight" ]] && filekey="$(node -e 'const j=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"));process.stdout.write(j.fileKey||"")' "$preflight" 2>/dev/null)" || true
fi
if [[ -z "$filekey" ]]; then echo "ERROR Could not resolve Figma filekey"; exit 2; fi

mkdir -p "$outDir"
[[ -f "$assetNamesSh" ]] && source "$assetNamesSh" || true

# Fetch SVG download URLs from Figma images API
tmpJson="$(mktemp)"
curl -sS -H "X-Figma-Token: $FIGMA_TOKEN" \
  "https://api.figma.com/v1/images/$filekey?ids=${nodeIds}&format=svg&use_absolute_bounds=true" \
  -o "$tmpJson"

downloaded=0
node -e '
const fs=require("fs");
const j=JSON.parse(fs.readFileSync(process.argv[1],"utf8"));
const map=(j&&j.images)?j.images:{};
for(const [id,url] of Object.entries(map)){
  if(url) process.stdout.write(id+"\t"+url+"\n");
}
' "$tmpJson" | while IFS=$'\t' read -r id url; do
  [[ -z "$id" || -z "$url" ]] && continue
  varname="ASSETNAME_${id//[^a-zA-Z0-9]/_}"
  filename="${(P)varname:-}"
  if [[ -z "$filename" ]]; then
    safeId="${id//[:\/]/-}"
    filename="${safeId}.svg"
  fi
  tmpSvg="$(mktemp)"
  if curl -sSL -o "$tmpSvg" "$url"; then
    mv "$tmpSvg" "$outDir/$filename"
    downloaded=$((downloaded+1))
  else
    rm -f "$tmpSvg"
  fi
done

rm -f "$tmpJson"
echo "export-vectors: downloaded $downloaded auto-detected SVG(s) to $outDir"
