#!/usr/bin/env bash
# Persist TPDB (and optional AE/Stash) API keys to config/api_keys.json
# Usage:
#   ./scripts/set_api_key.sh <tpdb-key> [ae-key] [stashdb-key]
#
# This writes config/api_keys.json (gitignored) and echoes an export line
# you can paste to set the env var for the current shell if desired.

set -euo pipefail

tpdb="${1:-}"
ae="${2:-}"
stash="${3:-}"

if [[ -z "$tpdb" ]]; then
  echo "Usage: $0 <tpdb-key> [ae-key] [stashdb-key]" >&2
  exit 1
fi

python - <<'PY' "$tpdb" "$ae" "$stash"
import json, sys, os

tpdb, ae, stash = sys.argv[1], sys.argv[2] or None, sys.argv[3] or None
path = os.path.join("config", "api_keys.json")
data = {}
if os.path.exists(path):
    try:
        with open(path, "r") as f:
            data = json.load(f)
    except Exception:
        data = {}

data["tpdb_api_key"] = tpdb
if ae:
    data["ae_api_key"] = ae
if stash:
    data["stashdb_api_key"] = stash

os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
    json.dump(data, f, indent=2)

print(f"Wrote {path}")
print(f'TPDB key set: {tpdb[:4]}... (hidden)')
PY

echo "To set the env var for this shell, run:"
echo "  export TPDB_API_KEY=\"${tpdb}\""
