#!/bin/bash

# Sync tbi-devops-environments documentation to S3
# Bucket: tbi-devops-agent-contexts
# Region: ca-central-1
# Profile: tbi-prod

set -e

BUCKET="tbi-devops-agent-contexts"
REGION="ca-central-1"
PROFILE="tbi-prod"
PREFIX="tbi-devops-environments"

echo "=== Syncing tbi-devops-environments to S3 ==="
echo "Bucket: s3://${BUCKET}"
echo "Region: ${REGION}"
echo "Profile: ${PROFILE}"
echo ""

# Check if AWS CLI is available
if ! command -v aws &> /dev/null; then
    echo "❌ AWS CLI not found. Please install it first."
    exit 1
fi

# Check if profile exists
if ! aws configure list-profiles | grep -q "^${PROFILE}$"; then
    echo "❌ AWS profile '${PROFILE}' not found."
    echo "Available profiles:"
    aws configure list-profiles
    exit 1
fi

echo "✓ AWS CLI found"
echo "✓ Profile '${PROFILE}' exists"
echo ""

# Sync documentation
echo "📄 Syncing documentation..."
aws s3 sync docs/ "s3://${BUCKET}/${PREFIX}/docs/" \
    --profile ${PROFILE} \
    --region ${REGION} \
    --exclude "*.swp" \
    --exclude ".DS_Store" \
    --delete

echo ""
echo "📄 Syncing scripts..."
aws s3 sync scripts/ "s3://${BUCKET}/${PREFIX}/scripts/" \
    --profile ${PROFILE} \
    --region ${REGION} \
    --exclude "*.swp" \
    --exclude ".DS_Store" \
    --delete

echo ""
echo "📄 Syncing .kiro configuration..."
aws s3 sync .kiro/ "s3://${BUCKET}/${PREFIX}/.kiro/" \
    --profile ${PROFILE} \
    --region ${REGION} \
    --exclude "*.swp" \
    --exclude ".DS_Store" \
    --delete

echo ""
echo "📄 Syncing integration files..."
aws s3 sync integration/ "s3://${BUCKET}/${PREFIX}/integration/" \
    --profile ${PROFILE} \
    --region ${REGION} \
    --exclude "*.swp" \
    --exclude ".DS_Store" \
    --delete

echo ""
echo "📄 Uploading README.md..."
aws s3 cp README.md "s3://${BUCKET}/${PREFIX}/README.md" \
    --profile ${PROFILE} \
    --region ${REGION}

echo ""
echo "✅ Sync complete!"
echo ""
echo "📊 Bucket contents:"
aws s3 ls "s3://${BUCKET}/${PREFIX}/" \
    --profile ${PROFILE} \
    --region ${REGION} \
    --recursive \
    --human-readable \
    --summarize

echo ""
echo "🔗 S3 URI: s3://${BUCKET}/${PREFIX}/"
echo "✓ All files synced successfully"
