#!/bin/bash

# Script to set up Fly.io storage for local testing
# This script helps you create a Fly.io storage bucket and configure it for local development

set -e

echo "🚀 Setting up Fly.io Storage for Local Testing"
echo ""

# Check if fly CLI is installed
if ! command -v fly &> /dev/null; then
    echo "❌ Fly.io CLI is not installed."
    echo "   Install it from: https://fly.io/docs/hands-on/install-flyctl/"
    exit 1
fi

echo "✅ Fly.io CLI is installed"
echo ""

# Check if user is authenticated
if ! fly auth whoami &> /dev/null; then
    echo "⚠️  You need to authenticate with Fly.io first."
    echo "   Run: fly auth login"
    exit 1
fi

echo "✅ Authenticated with Fly.io"
echo ""

# Get bucket name from user or use default
BUCKET_NAME="${1:-harmonic-saas-test-$(date +%s)}"

echo "📦 Creating Fly.io storage bucket: $BUCKET_NAME"
echo ""

# Create the storage bucket (don't exit on failure - bucket might already exist)
OUTPUT=$(fly storage create --public "$BUCKET_NAME" 2>&1) || {
    BUCKET_EXISTS_ERROR=$(echo "$OUTPUT" | grep -i "already exists" || true)
    if [ -n "$BUCKET_EXISTS_ERROR" ]; then
        echo "⚠️  Bucket already exists: $BUCKET_NAME"
        echo "   Continuing to check environment variables..."
        echo ""
        # Try to get credentials from existing bucket
        # Note: Fly.io doesn't provide a direct way to get credentials for existing buckets
        # So we'll check if .env already has them, otherwise prompt user
        OUTPUT=""  # Clear OUTPUT so we can check .env instead
    else
        echo "❌ Failed to create storage bucket"
        echo "$OUTPUT"
        exit 1
    fi
}

if [ -n "$OUTPUT" ]; then
    echo "$OUTPUT"
    echo ""
fi

# Extract credentials from output (compatible with both GNU and BSD grep)
ACCESS_KEY_ID=$(echo "$OUTPUT" | grep -E 'AWS_ACCESS_KEY_ID=' | sed -E 's/.*AWS_ACCESS_KEY_ID=([^[:space:]]+).*/\1/' | head -1)
SECRET_ACCESS_KEY=$(echo "$OUTPUT" | grep -E 'AWS_SECRET_ACCESS_KEY=' | sed -E 's/.*AWS_SECRET_ACCESS_KEY=([^[:space:]]+).*/\1/' | head -1)
ENDPOINT=$(echo "$OUTPUT" | grep -E 'AWS_ENDPOINT_URL_S3=' | sed -E 's/.*AWS_ENDPOINT_URL_S3=([^[:space:]]+).*/\1/' | head -1)
REGION=$(echo "$OUTPUT" | grep -E 'AWS_REGION=' | sed -E 's/.*AWS_REGION=([^[:space:]]+).*/\1/' | head -1)

# Set defaults if not found
ENDPOINT="${ENDPOINT:-https://fly.storage.tigris.dev}"
REGION="${REGION:-auto}"

# If bucket already exists and we don't have credentials from output, check .env file
if [ -z "$ACCESS_KEY_ID" ] || [ -z "$SECRET_ACCESS_KEY" ]; then
    ENV_FILE=".env"
    if [ -f "$ENV_FILE" ]; then
        # Try to extract from existing .env file
        EXISTING_ACCESS_KEY=$(grep -E '^FLY_STORAGE_ACCESS_KEY_ID=' "$ENV_FILE" | cut -d'=' -f2 | head -1)
        EXISTING_SECRET_KEY=$(grep -E '^FLY_STORAGE_SECRET_ACCESS_KEY=' "$ENV_FILE" | cut -d'=' -f2 | head -1)
        EXISTING_ENDPOINT=$(grep -E '^FLY_STORAGE_ENDPOINT=' "$ENV_FILE" | cut -d'=' -f2 | head -1)
        EXISTING_REGION=$(grep -E '^FLY_STORAGE_REGION=' "$ENV_FILE" | cut -d'=' -f2 | head -1)

        if [ -n "$EXISTING_ACCESS_KEY" ] && [ -n "$EXISTING_SECRET_KEY" ]; then
            echo "✅ Found existing credentials in .env file"
            ACCESS_KEY_ID="$EXISTING_ACCESS_KEY"
            SECRET_ACCESS_KEY="$EXISTING_SECRET_KEY"
            ENDPOINT="${EXISTING_ENDPOINT:-$ENDPOINT}"
            REGION="${EXISTING_REGION:-$REGION}"
        fi
    fi

    # If still no credentials, prompt user
    if [ -z "$ACCESS_KEY_ID" ] || [ -z "$SECRET_ACCESS_KEY" ]; then
        echo "⚠️  Could not automatically extract credentials."
        echo "   The bucket exists but credentials are not available."
        echo ""
        echo "   Please provide the credentials manually:"
        echo "   (You can find them in your Fly.io dashboard or from when the bucket was created)"
        echo ""
        read -p "   FLY_STORAGE_ACCESS_KEY_ID: " ACCESS_KEY_ID
        read -p "   FLY_STORAGE_SECRET_ACCESS_KEY: " SECRET_ACCESS_KEY
        read -p "   FLY_STORAGE_ENDPOINT [default: https://fly.storage.tigris.dev]: " INPUT_ENDPOINT
        read -p "   FLY_STORAGE_REGION [default: auto]: " INPUT_REGION

        ENDPOINT="${INPUT_ENDPOINT:-$ENDPOINT}"
        REGION="${INPUT_REGION:-$REGION}"

        if [ -z "$ACCESS_KEY_ID" ] || [ -z "$SECRET_ACCESS_KEY" ]; then
            echo "❌ Credentials are required. Exiting."
            exit 1
        fi
    fi
else
    echo "✅ Extracted credentials from Fly.io output"
    echo ""
fi

# Determine .env file location
ENV_FILE=".env"
if [ ! -f "$ENV_FILE" ]; then
    echo "📝 Creating .env file..."
    touch "$ENV_FILE"
fi

# Check if Fly.io storage config already exists
if grep -q "STORAGE_PROVIDER=fly-io" "$ENV_FILE" 2>/dev/null; then
    echo "⚠️  Fly.io storage configuration already exists in .env"
    read -p "   Do you want to update it? (y/n) " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "   Skipping .env update"
        exit 0
    fi

    # Remove old Fly.io storage config (macOS compatible)
    if [[ "$OSTYPE" == "darwin"* ]]; then
        sed -i '' '/^STORAGE_PROVIDER=fly-io$/d' "$ENV_FILE"
        sed -i '' '/^FLY_STORAGE_/d' "$ENV_FILE"
    else
        sed -i '/^STORAGE_PROVIDER=fly-io$/d' "$ENV_FILE"
        sed -i '/^FLY_STORAGE_/d' "$ENV_FILE"
    fi
fi

# Add Fly.io storage configuration
echo "" >> "$ENV_FILE"
echo "# Fly.io Storage Configuration (added by setup-fly-storage.sh)" >> "$ENV_FILE"
echo "STORAGE_PROVIDER=fly-io" >> "$ENV_FILE"
echo "FLY_STORAGE_ACCESS_KEY_ID=$ACCESS_KEY_ID" >> "$ENV_FILE"
echo "FLY_STORAGE_SECRET_ACCESS_KEY=$SECRET_ACCESS_KEY" >> "$ENV_FILE"
echo "FLY_STORAGE_ENDPOINT=$ENDPOINT" >> "$ENV_FILE"
echo "FLY_STORAGE_REGION=$REGION" >> "$ENV_FILE"
echo "FLY_STORAGE_BUCKET_NAME=$BUCKET_NAME" >> "$ENV_FILE"
echo "FLY_STORAGE_PUBLIC_URL_BASE=https://$BUCKET_NAME.fly.storage.tigris.dev" >> "$ENV_FILE"

echo "✅ Added Fly.io storage configuration to .env file"
echo ""
echo "📋 Configuration Summary:"
echo "   Storage Provider: fly-io"
echo "   Bucket Name: $BUCKET_NAME"
echo "   Public URL: https://$BUCKET_NAME.fly.storage.tigris.dev"
echo ""
echo "🎉 Setup complete! You can now test Fly.io storage locally."
echo ""
echo "💡 To test:"
echo "   1. Restart your dev server: pnpm dev"
echo "   2. Upload an image via /api/upload-image"
echo "   3. Check the returned URL - it should use Fly.io storage"
echo ""

