#!/bin/bash
set -e

source ./config.sh
echo "Using project: ${PROJECT_ID} in region: ${REGION}"

# Load from .env file if it exists
if [ -f ../.env ]; then
  echo "Loading API key from ../.env"
  export $(cat ../.env | grep ANTHROPIC_API_KEY | xargs)
fi

# Check if API key is available
if [ -z "$ANTHROPIC_API_KEY" ]; then
  echo "ERROR: ANTHROPIC_API_KEY not found"
  echo "Either:"
  echo "  1. export ANTHROPIC_API_KEY='your-api-key'"
  echo "  2. Create a .env file with: ANTHROPIC_API_KEY=your-api-key"
  exit 1
fi

# Enable required APIs
gcloud services enable \
  run.googleapis.com \
  cloudbuild.googleapis.com \
  artifactregistry.googleapis.com \
  secretmanager.googleapis.com \
  # firestore.googleapis.com

# Create Artifact Registry for containers
gcloud artifacts repositories create containers \
  --repository-format=docker \
  --location=${REGION}

# Create service account
gcloud iam service-accounts create claude-runner \
  --display-name="Claude Code Runner"

# Store Anthropic API key
echo -n "$ANTHROPIC_API_KEY" | gcloud secrets create anthropic-api-key \
  --data-file=-

# Grant permissions to service account
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:claude-runner@${PROJECT_ID}.iam.gserviceaccount.com" \
  --role="roles/datastore.user"

gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:claude-runner@${PROJECT_ID}.iam.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor"

gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:claude-runner@${PROJECT_ID}.iam.gserviceaccount.com" \
  --role="roles/storage.objectAdmin"