#!/usr/bin/env bash
set -euo pipefail

PROJECT_NAME=${PROJECT_NAME:-atproto-blog}
BUCKET_NAME=${BUCKET_NAME:-$PROJECT_NAME}
ARTIFACTS_BUCKET_NAME=${ARTIFACTS_BUCKET_NAME:-$PROJECT_NAME-artifacts}
AWS_REGION=${AWS_REGION:-us-east-1}
API_DID="did:web:localhost"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# --- Prerequisites ---

if [[ -z "${LOCALSTACK_AUTH_TOKEN:-}" ]]; then
  echo "❌ LOCALSTACK_AUTH_TOKEN is not set"
  echo "   export LOCALSTACK_AUTH_TOKEN=<your-token> before running this script."
  exit 1
fi

if [[ -z "${IFRAMELY_API_KEY:-}" ]]; then
  echo "❌ IFRAMELY_API_KEY is not set"
  echo "   export IFRAMELY_API_KEY=<your-key> before running this script."
  exit 1
fi

echo "🔍 Checking LocalStack..."
if ! curl -sf http://localhost:4566/_localstack/health > /dev/null; then
  echo "❌ LocalStack not reachable at localhost:4566"
  echo "   Run: make start-localstack"
  exit 1
fi
echo "✅ LocalStack reachable"

# --- Cleanup ---

delete_stack() {
  local stack="$1"
  if aws cloudformation describe-stacks --profile localstack --stack-name "$stack" &>/dev/null; then
    echo "🗑️  Deleting $stack..."
    aws cloudformation delete-stack --profile localstack --stack-name "$stack"
    aws cloudformation wait stack-delete-complete --profile localstack --stack-name "$stack"
  fi
}

echo ""
echo "🧹 Cleaning up existing stacks..."
delete_stack "$PROJECT_NAME-backfill-stack"
delete_stack "$PROJECT_NAME-indexer-stack"
delete_stack "$PROJECT_NAME-api-stack"
delete_stack "$PROJECT_NAME-artifacts-stack"
delete_stack "$PROJECT_NAME-s3-stack"
delete_stack "$PROJECT_NAME-dynamodb-stack"

# --- Infrastructure ---

echo ""
make -C "$SCRIPT_DIR" create-local-tables
echo ""
make -C "$SCRIPT_DIR" create-local-bucket
echo ""
make -C "$SCRIPT_DIR" create-local-artifacts ARTIFACTS_BUCKET_NAME="$ARTIFACTS_BUCKET_NAME"
echo ""
make -C "$SCRIPT_DIR" create-local-secret

IFRAMELY_SECRET_ARN=$(aws cloudformation describe-stacks --profile localstack \
  --stack-name "${PROJECT_NAME}-secrets-stack" \
  --query 'Stacks[0].Outputs[?OutputKey==`IframelySecretArn`].OutputValue' \
  --output text)
echo "🔑 Writing Iframely API key to secret..."
aws secretsmanager put-secret-value --profile localstack \
  --secret-id "$IFRAMELY_SECRET_ARN" \
  --secret-string "$IFRAMELY_API_KEY"

echo ""
make -C "$SCRIPT_DIR" create-local-api API_DID="$API_DID" IFRAMELY_SECRET_ARN="$IFRAMELY_SECRET_ARN"

# --- Lambda ---

echo ""
echo "🔧 Building and deploying blog API lambda..."
make -C "$SCRIPT_DIR" install-lambda
make -C "$SCRIPT_DIR" update-local-api

# --- Backfill ---

echo ""
make -C "$SCRIPT_DIR" deploy-local-backfill ARTIFACTS_BUCKET_NAME="$ARTIFACTS_BUCKET_NAME"

# --- Indexer ---
# LocalStack does not spin up real EC2 containers, so the indexer EC2 stack is
# skipped here. Run the indexer locally instead: make -C infra run-local-indexer

# --- API endpoint ---

# V1 REST API invoke URL: {apiId}.execute-api.{region}.localhost.localstack.cloud:4566/{stage}
API_ID=$(aws cloudformation describe-stacks --profile localstack \
  --stack-name "${PROJECT_NAME}-api-stack" \
  --query 'Stacks[0].Outputs[?OutputKey==`ApiId`].OutputValue' \
  --output text)
VITE_API_URL="http://${API_ID}.execute-api.${AWS_REGION}.localhost.localstack.cloud:4566/prod"

{
  echo "VITE_API_URL=${VITE_API_URL}"
  echo "VITE_API_DID=${API_DID}"
} > "$SCRIPT_DIR/../.env.local"
echo "✅ Wrote .env.local (VITE_API_URL=${VITE_API_URL})"

# --- Frontend ---

echo ""
echo "🏗️  Building frontend..."
(cd "$SCRIPT_DIR/.." && pnpm build)

echo ""
make -C "$SCRIPT_DIR" sync-site

# --- Serve ---

echo ""
pkill caddy 2>/dev/null || true
make -C "$SCRIPT_DIR" serve-local
