#!/bin/bash

# Language Services - AWS Deployment Script
# This script deploys the complete Language Services stack to AWS

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Default values
APP_NAME="language-services"
ENVIRONMENT="production"
AWS_REGION="${AWS_REGION:-us-east-1}"
STACK_NAME="${APP_NAME}-${ENVIRONMENT}"

# Function to print colored output
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Function to check if AWS CLI is configured
check_aws_cli() {
    if ! command -v aws &> /dev/null; then
        print_error "AWS CLI is not installed. Please install it first."
        exit 1
    fi

    if ! aws sts get-caller-identity &> /dev/null; then
        print_error "AWS CLI is not configured. Please run 'aws configure' first."
        exit 1
    fi

    print_info "AWS CLI is configured correctly"
}

# Function to check required parameters
check_parameters() {
    if [ -z "$LICENSE_KEY" ]; then
        print_error "LICENSE_KEY environment variable is required"
        exit 1
    fi

    if [ -z "$AUTH_PASSWORD" ]; then
        print_error "AUTH_PASSWORD environment variable is required"
        exit 1
    fi

    if [ -z "$AUTH_SECRET" ]; then
        print_error "AUTH_SECRET environment variable is required"
        exit 1
    fi

    if [ -z "$CONTAINER_IMAGE" ]; then
        print_error "CONTAINER_IMAGE environment variable is required"
        exit 1
    fi
}

# Function to deploy CloudFormation stack
deploy_stack() {
    print_info "Deploying CloudFormation stack: ${STACK_NAME}"

    aws cloudformation deploy \
        --template-file master-stack.yaml \
        --stack-name "${STACK_NAME}" \
        --region "${AWS_REGION}" \
        --capabilities CAPABILITY_NAMED_IAM \
        --parameter-overrides \
            AppName="${APP_NAME}" \
            Environment="${ENVIRONMENT}" \
            LicenseKey="${LICENSE_KEY}" \
            ContainerImage="${CONTAINER_IMAGE}" \
            AuthUsername="${AUTH_USERNAME:-admin}" \
            AuthPassword="${AUTH_PASSWORD}" \
            AuthSecret="${AUTH_SECRET}" \
            OpenAIApiKey="${OPENAI_API_KEY:-}" \
            TaskCPU="${TASK_CPU:-1024}" \
            TaskMemory="${TASK_MEMORY:-2048}" \
            DesiredCount="${DESIRED_COUNT:-2}" \
            DomainName="${DOMAIN_NAME:-}" \
            CertificateArn="${CERTIFICATE_ARN:-}" \
        --tags \
            Application="${APP_NAME}" \
            Environment="${ENVIRONMENT}" \
            ManagedBy="CloudFormation"

    print_info "Stack deployment initiated"
}

# Function to wait for stack completion
wait_for_stack() {
    print_info "Waiting for stack to complete..."

    aws cloudformation wait stack-create-complete \
        --stack-name "${STACK_NAME}" \
        --region "${AWS_REGION}" 2>/dev/null || \
    aws cloudformation wait stack-update-complete \
        --stack-name "${STACK_NAME}" \
        --region "${AWS_REGION}" 2>/dev/null || true

    # Get stack status
    STATUS=$(aws cloudformation describe-stacks \
        --stack-name "${STACK_NAME}" \
        --region "${AWS_REGION}" \
        --query 'Stacks[0].StackStatus' \
        --output text)

    if [[ "$STATUS" == *"COMPLETE"* ]] && [[ "$STATUS" != *"ROLLBACK"* ]]; then
        print_info "Stack deployment completed successfully!"
    else
        print_error "Stack deployment failed with status: ${STATUS}"
        exit 1
    fi
}

# Function to get stack outputs
get_outputs() {
    print_info "Stack Outputs:"
    echo ""

    aws cloudformation describe-stacks \
        --stack-name "${STACK_NAME}" \
        --region "${AWS_REGION}" \
        --query 'Stacks[0].Outputs[*].[OutputKey,OutputValue]' \
        --output table
}

# Main deployment function
main() {
    echo "=========================================="
    echo "  Language Services - AWS Deployment"
    echo "=========================================="
    echo ""

    check_aws_cli
    check_parameters

    print_info "Deployment Configuration:"
    echo "  App Name:     ${APP_NAME}"
    echo "  Environment:  ${ENVIRONMENT}"
    echo "  Region:       ${AWS_REGION}"
    echo "  Stack Name:   ${STACK_NAME}"
    echo ""

    deploy_stack
    wait_for_stack
    get_outputs

    echo ""
    print_info "Deployment complete!"
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --app-name)
            APP_NAME="$2"
            shift 2
            ;;
        --environment)
            ENVIRONMENT="$2"
            shift 2
            ;;
        --region)
            AWS_REGION="$2"
            shift 2
            ;;
        --help)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --app-name NAME       Application name (default: language-services)"
            echo "  --environment ENV     Environment (default: production)"
            echo "  --region REGION       AWS Region (default: us-east-1)"
            echo ""
            echo "Required Environment Variables:"
            echo "  LICENSE_KEY           License key for the application"
            echo "  AUTH_PASSWORD         Password for application authentication"
            echo "  AUTH_SECRET           JWT secret for authentication"
            echo "  CONTAINER_IMAGE       Docker image URI"
            echo ""
            echo "Optional Environment Variables:"
            echo "  AUTH_USERNAME         Username (default: admin)"
            echo "  OPENAI_API_KEY        OpenAI API key"
            echo "  TASK_CPU              CPU units (default: 1024)"
            echo "  TASK_MEMORY           Memory in MB (default: 2048)"
            echo "  DESIRED_COUNT         Number of tasks (default: 2)"
            echo "  DOMAIN_NAME           Custom domain name"
            echo "  CERTIFICATE_ARN       ACM certificate ARN"
            exit 0
            ;;
        *)
            print_error "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Update stack name based on app name and environment
STACK_NAME="${APP_NAME}-${ENVIRONMENT}"

# Run main function
main
