#!/usr/bin/env zsh
set -euo pipefail

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

if [[ -z "$campaign" || -z "$page" ]]; then
  echo "usage: scripts/export-frame-jsons.v0.1.3.zsh <campaign> <page> [desktop_url] [mobile_url]"
  exit 2
fi

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

extract_file_key(){ printf '%s' "$1" | sed -En 's#^(https?://|figma://)[^/]+/(file|design|proto)/([A-Za-z0-9_-]+).*#\3#p' | head -n1; }
extract_node_id(){ printf '%s' "$1" | sed -En 's#.*[?#]node-id=([^&]+).*#\1#p' | head -n1; }

# STREAM_PATH_NOTE: "awareness" is the hardcoded default stream name.
# If multi-stream support is added, replace "awareness" with the stream name
# from preflight.json (same as resolveStreamFolderName in the generator).
preflight_json="campaigns/content/$campaign/awareness/_sologen/json/preflight.json"
pf_filekey=""
pf_desktop_id=""
pf_mobile_id=""
if [[ -s "$preflight_json" ]]; then
  pf_data="$(node -e '
const fs=require("fs");
const path=process.argv[1];
const page=process.argv[2];
try{
  const j=JSON.parse(fs.readFileSync(path,"utf8"));
  const screens=Array.isArray(j?.screens)?j.screens:[];
  const hit=screens.find(s=>String(s?.id||"")===String(page));
  if(!hit){ process.exit(0); }
  const out={
    fileKey: j?.fileKey || "",
    desktopUrl: hit.desktopUrl || "",
    mobileUrl: hit.mobileUrl || "",
    desktopId: hit.desktopId || "",
    mobileId: hit.mobileId || ""
  };
  process.stdout.write(JSON.stringify(out));
}catch(_e){}
' "$preflight_json" "$page")"
  if [[ -n "$pf_data" ]]; then
    pf_pair="$(node -e 'const x=JSON.parse(process.argv[1]||"{}");process.stdout.write((x.desktopUrl||"")+"\t"+(x.mobileUrl||"")+"\t"+(x.desktopId||"")+"\t"+(x.mobileId||"")+"\t"+(x.fileKey||""));' "$pf_data")"
    pf_desktop="${pf_pair%%$'\t'*}"
    rest="${pf_pair#*$'\t'}"
    pf_mobile="${rest%%$'\t'*}"
    rest="${rest#*$'\t'}"
    pf_desktop_id="${rest%%$'\t'*}"
    rest="${rest#*$'\t'}"
    pf_mobile_id="${rest%%$'\t'*}"
    pf_filekey="${rest#*$'\t'}"
    [[ -z "$desktop_url" ]] && desktop_url="$pf_desktop"
    [[ -z "$mobile_url" ]] && mobile_url="$pf_mobile"
  fi
fi

filekey_d="$(extract_file_key "$desktop_url")"
filekey_m="$(extract_file_key "$mobile_url")"
nodeid_d_raw="$(extract_node_id "$desktop_url")"
nodeid_m_raw="$(extract_node_id "$mobile_url")"

[[ -z "$filekey_d" && -n "$pf_filekey" ]] && filekey_d="$pf_filekey"
[[ -z "$filekey_m" && -n "$pf_filekey" ]] && filekey_m="$pf_filekey"
[[ -z "$filekey_d" && -n "${FIGMA_FILE_KEY:-}" ]] && filekey_d="${FIGMA_FILE_KEY}"
[[ -z "$filekey_m" && -n "${FIGMA_FILE_KEY:-}" ]] && filekey_m="${FIGMA_FILE_KEY}"
[[ -z "$nodeid_d_raw" && -n "$pf_desktop_id" ]] && nodeid_d_raw="${pf_desktop_id//:/-}"
[[ -z "$nodeid_m_raw" && -n "$pf_mobile_id" ]] && nodeid_m_raw="${pf_mobile_id//:/-}"

if [[ -z "$filekey_d" || -z "$nodeid_d_raw" ]]; then
  echo "ERROR Desktop frame not resolved. Provide desktop URL, or ensure preflight has desktopId and fileKey (or set FIGMA_FILE_KEY)."
  exit 3
fi
if [[ -z "$filekey_m" || -z "$nodeid_m_raw" ]]; then
  echo "ERROR Mobile frame not resolved. Provide mobile URL, or ensure preflight has mobileId and fileKey (or set FIGMA_FILE_KEY)."
  exit 3
fi

# Normalize node IDs (Figma URLs use 8003-1136; API needs 8003:1136)
nodeid_d="${nodeid_d_raw//-/:}"
nodeid_m="${nodeid_m_raw//-/:}"

outdir="campaigns/content/$campaign/awareness/_sologen/json/$page"
mkdir -p "$outdir"

if [[ -s "$preflight_json" && -n "$filekey_d" ]]; then
  node -e '
const fs=require("fs");
const path=process.argv[1];
const page=process.argv[2];
const fileKey=process.argv[3];
const desktopId=process.argv[4];
const mobileId=process.argv[5];
const mkUrl=(k,id)=>`https://www.figma.com/design/${k}/?node-id=${encodeURIComponent(String(id||"").replace(/[:/]/g,"-"))}`;
try{
  const j=JSON.parse(fs.readFileSync(path,"utf8"));
  if(!j.fileKey) j.fileKey=fileKey;
  const screens=Array.isArray(j.screens)?j.screens:[];
  const s=screens.find(x=>String(x?.id||"")===String(page));
  if(s){
    if(!s.desktopUrl && desktopId) s.desktopUrl=mkUrl(fileKey, desktopId);
    if(!s.mobileUrl && mobileId) s.mobileUrl=mkUrl(fileKey, mobileId);
  }
  fs.writeFileSync(path, JSON.stringify(j,null,2));
}catch(_e){}
' "$preflight_json" "$page" "$filekey_d" "$nodeid_d" "$nodeid_m"
fi

echo "DESK key=$filekey_d node=$nodeid_d (from $nodeid_d_raw)"
echo "MOB  key=$filekey_m node=$nodeid_m (from $nodeid_m_raw)"
echo "FIGMA_TOKEN len=${#FIGMA_TOKEN}"

desk_url_api="https://api.figma.com/v1/files/$filekey_d/nodes?ids=$nodeid_d"
mob_url_api="https://api.figma.com/v1/files/$filekey_m/nodes?ids=$nodeid_m"

echo "curl DESKTOP: $desk_url_api"
echo "curl MOBILE:  $mob_url_api"

# --- DESKTOP ---
curl -sS --http1.1 \
  -D "$outdir/.hdr_desktop" \
  -H "X-Figma-Token: $FIGMA_TOKEN" \
  "$desk_url_api" \
  -o "$outdir/desktop.json" \
  || {
    echo "ERROR DESKTOP request failed"
    echo "---- DESKTOP headers ----"
    cat "$outdir/.hdr_desktop" 2>/dev/null || true
    exit 4
  }

# --- MOBILE ---
curl -sS --http1.1 \
  -D "$outdir/.hdr_mobile" \
  -H "X-Figma-Token: $FIGMA_TOKEN" \
  "$mob_url_api" \
  -o "$outdir/mobile.json" \
  || {
    echo "ERROR MOBILE request failed"
    echo "---- MOBILE headers ----"
    cat "$outdir/.hdr_mobile" 2>/dev/null || true
    exit 4
  }

printf "HTTP_DESKTOP: "; head -n 1 "$outdir/.hdr_desktop" || true
printf "HTTP_MOBILE:  "; head -n 1 "$outdir/.hdr_mobile"  || true

# --- Hard safety checks ---
if [[ ! -s "$outdir/desktop.json" ]]; then
  echo "ERROR Empty desktop.json"
  exit 5
fi

if [[ ! -s "$outdir/mobile.json" ]]; then
  echo "ERROR Empty mobile.json"
  exit 5
fi

# Fail fast if API returned an error payload instead of document JSON
if grep -q '"status":' "$outdir/desktop.json" 2>/dev/null; then
  echo "ERROR desktop.json looks like an API error payload:"
  head -c 200 "$outdir/desktop.json"; echo
  exit 6
fi

if grep -q '"status":' "$outdir/mobile.json" 2>/dev/null; then
  echo "ERROR mobile.json looks like an API error payload:"
  head -c 200 "$outdir/mobile.json"; echo
  exit 6
fi

echo "Wrote $outdir/desktop.json"
echo "Wrote $outdir/mobile.json"
