#!/bin/sh
# The factory keeps the crew's token in a file, never in a station's settings, and Claude Code hides
# variables named *TOKEN* from this helper, so the file's path comes in TARES_FACTORY_CRED_FILE.
f=${TARES_FACTORY_CRED_FILE:-}
if [ -n "$f" ] && [ -r "$f" ]; then
  tok=$(tr -d '[:space:]' < "$f")
  if [ -n "$tok" ]; then
    printf '{"Authorization":"Bearer %s"}\n' "$tok"
    exit 0
  fi
fi
# Outside the factory: the key `tares login` saved (TR-492), only when Claude Code is calling that
# same workspace's MCP endpoint, so the key never goes to another address.
login="${TARES_HOME:-$HOME/.tares}/login.json"
if [ -n "${CLAUDE_CODE_MCP_SERVER_URL:-}" ] && [ -r "$login" ] && command -v python3 >/dev/null 2>&1; then
  python3 -I - "$login" "$CLAUDE_CODE_MCP_SERVER_URL" <<'EOF' && exit 0
import json, sys
try:
    d = json.load(open(sys.argv[1]))
    cell, key = str(d.get("cell_url") or "").rstrip("/"), str(d.get("key") or "")
except Exception:
    sys.exit(1)
if not cell or not key or sys.argv[2].rstrip("/") != cell + "/mcp":
    sys.exit(1)
print(json.dumps({"Authorization": "Bearer " + key}))
EOF
fi
echo '{}'
