#!/bin/bash

# --- Configuration ---
# The name of your Lambda function
FUNCTION_NAME="tg-bot-lambda-template"

# The AWS region where your Lambda function is deployed
AWS_REGION="us-east-1"

# The Python runtime for your Lambda function
RUNTIME="python3.13"

# The handler for your Lambda function
HANDLER="lambda_function.lambda_handler"

# The name of the deployment package
ZIP_FILE="deployment.zip"

# The directory to build the deployment package in
BUILD_DIR="build"

# --- Script ---

# Function to display colored output
print_color() {
    COLOR=$1
    MESSAGE=$2
    echo -e "\e[${COLOR}m${MESSAGE}\e[0m"
}

# Exit immediately if a command exits with a non-zero status
set -e

print_color "36" "Starting Lambda deployment process..."

# 1. Clean up previous build artifacts
print_color "33" "[1/5] Cleaning up previous build artifacts..."
rm -rf "${BUILD_DIR}" "${ZIP_FILE}"
mkdir -p "${BUILD_DIR}"

# 2. Install dependencies
print_color "33" "[2/5] Installing dependencies from requirements.txt..."
pip install \
    --platform manylinux2014_x86_64 \
    --python-version 3.13 \
    --only-binary=:all: \
    --target "./${BUILD_DIR}" \
    -r requirements.txt

# 3. Copy application code
print_color "33" "[3/5] Copying application code..."
cp -r core/ "${BUILD_DIR}/core/"
cp -r handlers/ "${BUILD_DIR}/handlers/"
cp -r utils/ "${BUILD_DIR}/utils/"
cp -r states/ "${BUILD_DIR}/states/"
cp -r keyboards/ "${BUILD_DIR}/keyboards/"
cp lambda_function.py "${BUILD_DIR}/"

# 4. Create deployment package
print_color "33" "[4/5] Creating deployment package (${ZIP_FILE})..."
cd "${BUILD_DIR}"
zip -r "../${ZIP_FILE}" .
cd ..

# 5. Optional: Deploy to AWS
print_color "33" "[5/5] Deployment package created successfully!"

read -p "Do you want to deploy to AWS now? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
    print_color "36" "Deploying to AWS and configuring environment..."

    # Check if .env.prod file exists
    if [ ! -f ".env.prod" ]; then
        print_color "31" "Error: .env.prod file not found. Please create it with your production settings."
        exit 1
    fi

    # Source the production environment variables
    export $(grep -v '^#' .env.prod | xargs)

    # Check for required variables
    if [ -z "$BOT_TOKEN" ] || [ -z "$LAMBDA_URL" ] || [ -z "$SECRET_KEY" ]; then
        print_color "31" "Error: BOT_TOKEN, LAMBDA_URL, and SECRET_KEY must be set in .env.prod"
        exit 1
    fi

    # Deploy the function code
    print_color "36" "Updating function code..."
    aws lambda update-function-code --function-name "${FUNCTION_NAME}" --zip-file "fileb://${ZIP_FILE}" --region "${AWS_REGION}"

    # Wait for the function to be ready
    aws lambda wait function-updated --function-name "${FUNCTION_NAME}" --region "${AWS_REGION}"

    # Update Lambda environment variables from the .env.prod file
    print_color "36" "Updating environment variables..."
    aws lambda update-function-configuration --function-name "${FUNCTION_NAME}" --region "${AWS_REGION}" \
        --environment "Variables={BOT_TOKEN=${BOT_TOKEN},LAMBDA_URL=${LAMBDA_URL},SECRET_KEY=${SECRET_KEY}}"

    # Wait for the environment update to complete
    aws lambda wait function-updated --function-name "${FUNCTION_NAME}" --region "${AWS_REGION}"

    # Ask the user if they want to set the webhook
    read -p "Deployment successful. Do you want to set the Telegram webhook now? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]
    then
        print_color "36" "Setting Telegram webhook..."
        PAYLOAD="{\"command\":\"set_webhook\",\"secret\":\"${SECRET_KEY}\"}"
        aws lambda invoke \
          --function-name "${FUNCTION_NAME}" \
          --payload "${PAYLOAD}" \
          --cli-binary-format raw-in-base64-out \
          --region "${AWS_REGION}" \
          response.json
        print_color "32" "Webhook set successfully. See response.json for details."
    else
        print_color "32" "To set the webhook manually, run the following command:"
        PAYLOAD_TEXT='{"command":"set_webhook","secret":"'${SECRET_KEY}'"}'
        print_color "34" "aws lambda invoke --function-name ${FUNCTION_NAME} --payload '${PAYLOAD_TEXT}' --cli-binary-format raw-in-base64-out --region ${AWS_REGION} response.json"
    fi

    print_color "36" "Cleaning up build artifacts..."
    rm -rf "${BUILD_DIR}" "${ZIP_FILE}"
else
    print_color "32" "Deployment skipped. Your package is ready for manual upload: ${ZIP_FILE}"
fi

print_color "32" "Done!"
