#!/bin/bash
#
# figma-token.sh
# The one place a Tier 2 Figma request gets its credential.
#
# Sourced by every Tier 2 fetcher (fetch-figma-annotations.sh,
# figma-screenshot.sh). It exists because those two each carried their own copy
# of the lookup, and a copy drifts: when the key a fetcher read was renamed,
# only one of the three places learned about it, and a valid PAT read as
# `missing-token` while the error text named a key that no longer existed. One
# copy of the lookup cannot drift from itself.
#
# Tier 2 is only reached when Tier 1 (Figma MCP) is unreachable; see the Figma
# Access Tier rule in multi-agent-refs/rules.md for the chain and the
# expired-token decision that gates the move to Tier 3.
#
# Resolution goes through the account resolver, which owns the whole question:
# which account answers for Figma, which store item holds its PAT, whether the
# environment carries one instead, and whether the URL being called is one that
# account may be sent to. No logical key, no store path and no Keychain service
# name appears here, which is what keeps the Synced Command Hygiene rule
# satisfied by construction rather than by review.
#
# Usage:
#   figma_cfg "https://api.figma.com/v1/..."   # sets FIGMA_CFG, or returns non-zero
#   curl --config "$FIGMA_CFG" ...
#
# The credential never reaches a shell variable: it is written into a curl
# config that also carries the URL it is for, so the two cannot be separated
# and a redirect is refused rather than followed with the header on.

_MA_FT_HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/dev/null
if [ -f "$_MA_FT_HERE/user-facing.sh" ]; then . "$_MA_FT_HERE/user-facing.sh"; else . "$HOME/.claude/lib/user-facing.sh"; fi
# shellcheck source=/dev/null
if [ -f "$_MA_FT_HERE/_service-account.sh" ]; then
  . "$_MA_FT_HERE/_service-account.sh"
elif [ -f "$HOME/.claude/lib/_service-account.sh" ]; then
  . "$HOME/.claude/lib/_service-account.sh"
fi

# figma_cfg <url>
# Sets FIGMA_CFG to a curl config carrying the PAT to that URL, or returns
# non-zero with the refusal available from sa_reason / sa_explain.
#
# It sets a variable rather than printing one because a caller reading it
# through a command substitution runs in a subshell, where a refusal branch's
# `exit` ends the subshell and the caller carries on unauthenticated.
# shellcheck disable=SC2034  # read by the fetchers that source this file
FIGMA_CFG=""
figma_cfg() {
  if ! command -v sa_cfg >/dev/null 2>&1; then
    return 2
  fi
  # shellcheck disable=SC2034  # read by the fetchers that source this file
  FIGMA_CFG="$(sa_cfg figma "$1" figma-pat)"
}

# figma_token_remediation
# The one place the "how do I fix this" sentence is written, so a fetcher can
# never name a key that does not exist.
figma_token_remediation() {
  printf 'no Figma PAT for Tier 2. Add a Figma account with %s, or export FIGMA_PAT.' "$(ma_command setup)"
}
