#!/bin/bash
#
# figma-token.sh
# Single resolution point for the Tier 2 Figma Personal Access Token.
#
# Sourced by every Tier 2 fetcher (fetch-figma-annotations.sh,
# figma-screenshot.sh). It exists because those two each carried their own copy
# of this lookup: when `migrate-prefs.mjs` consolidated
# `keychainMapping.figma_pat` into `keychainMapping.figma` and deleted the old
# key, only the migration was updated. Both fetchers kept reading the deleted
# key, so every migrated install reported `missing-token` while a valid PAT sat
# under the new name - and the error text told the user to map the key the
# migration had just removed. 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 order, first non-empty wins:
#   1. credential-store.sh get figma      - the canonical logical key
#   2. credential-store.sh get figma_pat  - pre-v13.6 installs that never migrated
#   3. $FIGMA_PAT                         - env fallback for CI and one-shot runs
#
# Logical keys are passed through verbatim. credential-store.sh owns the
# `prefs.global.keychainMapping` indirection, so resolving the mapping here as
# well would reintroduce the duplication this file exists to remove. No literal
# Keychain service name appears here, which keeps the Synced Command Hygiene
# rule satisfied.
#
# Requires `$CRED_STORE` to already be resolved (via credential-store-resolver.sh).
# An unset or non-executable CRED_STORE is tolerated: resolution falls through to
# the env fallback so a keychain-less CI box still works.

# The canonical key first, the legacy key second. Space-separated so the loop
# below stays POSIX-ish and works under bash 3.2 (stock macOS).
FIGMA_TOKEN_LOGICAL_KEYS="${FIGMA_TOKEN_LOGICAL_KEYS:-figma figma_pat}"

# resolve_figma_token
# Prints the token on stdout and returns 0, or prints nothing and returns 1.
resolve_figma_token() {
  local key tok
  if [ -n "${CRED_STORE:-}" ] && [ -x "${CRED_STORE:-}" ]; then
    for key in $FIGMA_TOKEN_LOGICAL_KEYS; do
      tok=$("$CRED_STORE" get "$key" 2>/dev/null || true)
      if [ -n "$tok" ]; then
        printf '%s' "$tok"
        return 0
      fi
    done
  fi
  if [ -n "${FIGMA_PAT:-}" ]; then
    printf '%s' "$FIGMA_PAT"
    return 0
  fi
  return 1
}

# figma_token_remediation
# The one place the "how do I fix this" sentence is written, so a fetcher can
# never name a key the migration deleted.
figma_token_remediation() {
  printf 'no Figma PAT for Tier 2. Map prefs.global.keychainMapping.figma (run /multi-agent:setup), or export FIGMA_PAT.'
}
