#!/usr/bin/env bash
# provision-project-keys.sh — create per-project API keys and store in GCP Secret Manager
#
# Usage: STEMEDB_ADMIN_KEY=steme_live_... ./scripts/provision-project-keys.sh projects.txt
# projects.txt: one project slug per line (e.g. "my-app", "another-project")
#
# Requires: curl, jq, gcloud (authenticated)

set -euo pipefail

STEMEDB_URL="${STEMEDB_URL:-https://stemedb.threesix.ai}"
ADMIN_KEY="${STEMEDB_ADMIN_KEY:?Set STEMEDB_ADMIN_KEY to a root/admin API key}"
PROJECTS_FILE="${1:?Usage: $0 <projects-file>}"
GCP_PROJECT="${GCP_PROJECT:-orchard9}"

echo "Provisioning keys against: $STEMEDB_URL"
echo "GCP project for secrets: $GCP_PROJECT"
echo ""

while IFS= read -r project; do
    [[ -z "$project" || "$project" =~ ^# ]] && continue

    echo "→ Provisioning: $project"

    response=$(curl -sf -X POST "$STEMEDB_URL/v1/admin/api-keys" \
        -H "X-API-Key: $ADMIN_KEY" \
        -H "Content-Type: application/json" \
        -d "{\"environment\":\"live\",\"label\":\"project-$project\",\"role\":\"write_agent\"}") \
        || { echo "  ERROR: API call failed for $project"; continue; }

    key=$(echo "$response" | jq -r '.key')

    if [[ -z "$key" || "$key" == "null" ]]; then
        echo "  ERROR: no key returned for $project"
        continue
    fi

    secret_name="stemedb-key-$project"
    if gcloud secrets describe "$secret_name" --project="$GCP_PROJECT" &>/dev/null; then
        echo -n "$key" | gcloud secrets versions add "$secret_name" \
            --project="$GCP_PROJECT" --data-file=-
        echo "  Updated existing secret: $secret_name"
    else
        echo -n "$key" | gcloud secrets create "$secret_name" \
            --project="$GCP_PROJECT" \
            --replication-policy=automatic \
            --data-file=-
        echo "  Created new secret: $secret_name"
    fi
done < "$PROJECTS_FILE"

echo ""
echo "Done. Projects retrieve their keys with:"
echo "  gcloud secrets versions access latest --secret=stemedb-key-<project> --project=$GCP_PROJECT"
