#!/bin/bash
set -e

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

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

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Laravel Application Deployment Script${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

# Check prerequisites
echo -e "${YELLOW}Checking prerequisites...${NC}"

if ! command -v terraform &> /dev/null; then
    echo -e "${RED}Error: Terraform is not installed${NC}"
    exit 1
fi

if ! command -v az &> /dev/null; then
    echo -e "${RED}Error: Azure CLI is not installed${NC}"
    exit 1
fi

if ! command -v kubectl &> /dev/null; then
    echo -e "${RED}Error: kubectl is not installed${NC}"
    exit 1
fi

if ! command -v docker &> /dev/null; then
    echo -e "${RED}Error: Docker is not installed${NC}"
    exit 1
fi

echo -e "${GREEN}✓ All prerequisites are installed${NC}"
echo ""

# Check if logged into Azure
echo -e "${YELLOW}Checking Azure login status...${NC}"
if ! az account show &> /dev/null; then
    echo -e "${RED}Error: Not logged into Azure. Please run 'az login'${NC}"
    exit 1
fi

CURRENT_SUBSCRIPTION=$(az account show --query name -o tsv)
echo -e "${GREEN}✓ Logged into Azure (Subscription: $CURRENT_SUBSCRIPTION)${NC}"
echo ""

# Check if terraform.tfvars exists
if [ ! -f "$TERRAFORM_DIR/terraform.tfvars" ]; then
    echo -e "${RED}Error: terraform.tfvars not found${NC}"
    echo -e "${YELLOW}Please create terraform.tfvars from terraform.tfvars.example${NC}"
    echo -e "${YELLOW}cp $TERRAFORM_DIR/terraform.tfvars.example $TERRAFORM_DIR/terraform.tfvars${NC}"
    exit 1
fi

# Check if Docker image is specified
DOCKER_IMAGE=$(grep 'docker_image' "$TERRAFORM_DIR/terraform.tfvars" | cut -d'"' -f2)
if [ -z "$DOCKER_IMAGE" ] || [ "$DOCKER_IMAGE" == "myregistry.azurecr.io/laravel-app:latest" ]; then
    echo -e "${YELLOW}Warning: Docker image not configured in terraform.tfvars${NC}"
    echo -e "${YELLOW}Please update the docker_image variable before deploying${NC}"
    read -p "Do you want to build and push the Docker image now? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}Please provide the following information:${NC}"
        read -p "Azure Container Registry name (e.g., myregistry): " ACR_NAME
        read -p "Image name (e.g., laravel-app): " IMAGE_NAME
        read -p "Image tag (default: latest): " IMAGE_TAG
        IMAGE_TAG=${IMAGE_TAG:-latest}

        DOCKER_IMAGE="$ACR_NAME.azurecr.io/$IMAGE_NAME:$IMAGE_TAG"

        echo -e "${YELLOW}Building Docker image...${NC}"
        cd "$PROJECT_ROOT"
        docker build -t "$DOCKER_IMAGE" .

        echo -e "${YELLOW}Logging into Azure Container Registry...${NC}"
        az acr login --name "$ACR_NAME"

        echo -e "${YELLOW}Pushing Docker image...${NC}"
        docker push "$DOCKER_IMAGE"

        echo -e "${GREEN}✓ Docker image pushed successfully${NC}"

        # Update terraform.tfvars
        sed -i.bak "s|docker_image = \".*\"|docker_image = \"$DOCKER_IMAGE\"|" "$TERRAFORM_DIR/terraform.tfvars"
        echo -e "${GREEN}✓ Updated terraform.tfvars with new Docker image${NC}"
        echo ""
    else
        echo -e "${RED}Deployment cancelled. Please configure docker_image in terraform.tfvars${NC}"
        exit 1
    fi
fi

# Generate Laravel APP_KEY if needed
APP_KEY=$(grep 'app_key' "$TERRAFORM_DIR/terraform.tfvars" | cut -d'"' -f2)
if [ -z "$APP_KEY" ] || [ "$APP_KEY" == "base64:YOUR_APP_KEY_HERE" ]; then
    echo -e "${YELLOW}Generating Laravel APP_KEY...${NC}"
    cd "$PROJECT_ROOT"
    NEW_APP_KEY=$(php artisan key:generate --show)
    sed -i.bak "s|app_key = \".*\"|app_key = \"$NEW_APP_KEY\"|" "$TERRAFORM_DIR/terraform.tfvars"
    echo -e "${GREEN}✓ Generated and saved APP_KEY${NC}"
    echo ""
fi

# Change to Terraform directory
cd "$TERRAFORM_DIR"

# Initialize Terraform
echo -e "${YELLOW}Initializing Terraform...${NC}"
terraform init

# Validate Terraform configuration
echo -e "${YELLOW}Validating Terraform configuration...${NC}"
terraform validate

# Plan deployment
echo -e "${YELLOW}Planning deployment...${NC}"
terraform plan -out=tfplan

# Confirm deployment
echo ""
echo -e "${YELLOW}========================================${NC}"
echo -e "${YELLOW}Ready to deploy!${NC}"
echo -e "${YELLOW}========================================${NC}"
read -p "Do you want to proceed with the deployment? (yes/no) " -r
echo
if [[ ! $REPLY =~ ^[Yy][Ee][Ss]$ ]]; then
    echo -e "${RED}Deployment cancelled${NC}"
    rm -f tfplan
    exit 1
fi

# Apply Terraform
echo -e "${YELLOW}Applying Terraform configuration...${NC}"
terraform apply tfplan

# Clean up plan file
rm -f tfplan

# Get outputs
echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Deployment completed successfully!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

terraform output deployment_instructions

# Configure kubectl
echo ""
echo -e "${YELLOW}Configuring kubectl...${NC}"
RESOURCE_GROUP=$(terraform output -raw resource_group_name)
AKS_CLUSTER=$(terraform output -raw aks_cluster_name)
az aks get-credentials --resource-group "$RESOURCE_GROUP" --name "$AKS_CLUSTER" --overwrite-existing
echo -e "${GREEN}✓ kubectl configured${NC}"

# Wait for pods to be ready
echo ""
echo -e "${YELLOW}Waiting for application pods to be ready...${NC}"
APP_NAMESPACE=$(terraform output -raw app_namespace)
kubectl wait --for=condition=ready pod -l app=$(terraform output -raw app_service_name | sed 's/-service//') -n "$APP_NAMESPACE" --timeout=300s || true

# Show pod status
echo ""
echo -e "${YELLOW}Application pod status:${NC}"
kubectl get pods -n "$APP_NAMESPACE"

echo ""
echo -e "${GREEN}Deployment script completed!${NC}"
