#!/bin/bash
# ==============================================================================
# MORPH-SPEC - Deploy Script
# Automated deployment of Azure infrastructure
# ==============================================================================

set -e  # Exit on error

# ==============================================================================
# CONFIGURATION
# ==============================================================================

# Required variables (override via environment)
APP_NAME="${APP_NAME:-myapp}"
ENVIRONMENT="${ENVIRONMENT:-dev}"
LOCATION="${LOCATION:-eastus}"
SUBSCRIPTION_ID="${SUBSCRIPTION_ID:-}"

# Optional variables
HOSTING_TYPE="${HOSTING_TYPE:-appservice}"  # appservice or containerapp
APP_SERVICE_SKU="${APP_SERVICE_SKU:-F1}"
CONTAINER_IMAGE="${CONTAINER_IMAGE:-mcr.microsoft.com/hello-world:latest}"

# Derived variables
RESOURCE_GROUP="rg-${APP_NAME}-${ENVIRONMENT}"
DEPLOYMENT_NAME="deploy-${APP_NAME}-$(date +%Y%m%d-%H%M%S)"

# ==============================================================================
# COLORS
# ==============================================================================

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# ==============================================================================
# FUNCTIONS
# ==============================================================================

log_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

log_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

log_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

log_error() {
    echo -e "${RED}❌ $1${NC}"
}

check_prerequisites() {
    log_info "Checking prerequisites..."

    # Check Azure CLI
    if ! command -v az &> /dev/null; then
        log_error "Azure CLI not found. Install from: https://aka.ms/azure-cli"
        exit 1
    fi

    # Check login
    if ! az account show &> /dev/null; then
        log_error "Not logged in to Azure. Run: az login"
        exit 1
    fi

    # Set subscription if provided
    if [ -n "$SUBSCRIPTION_ID" ]; then
        log_info "Setting subscription to: $SUBSCRIPTION_ID"
        az account set --subscription "$SUBSCRIPTION_ID"
    fi

    log_success "Prerequisites checked"
}

create_resource_group() {
    log_info "Creating resource group: $RESOURCE_GROUP"

    if az group exists -n "$RESOURCE_GROUP" | grep -q true; then
        log_warning "Resource group already exists"
    else
        az group create \
            --name "$RESOURCE_GROUP" \
            --location "$LOCATION" \
            --tags \
                environment="$ENVIRONMENT" \
                application="$APP_NAME" \
                managedBy="bicep" \
                framework="morph-spec"

        log_success "Resource group created"
    fi
}

generate_sql_password() {
    # Generate secure random password
    SQL_PASSWORD=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
    log_success "SQL password generated (stored in Key Vault after deploy)"
}

deploy_infrastructure() {
    log_info "Deploying infrastructure..."
    log_info "  App Name: $APP_NAME"
    log_info "  Environment: $ENVIRONMENT"
    log_info "  Hosting Type: $HOSTING_TYPE"
    log_info "  Location: $LOCATION"

    # Prepare parameters file
    PARAMS_FILE="parameters.${ENVIRONMENT}.json"

    if [ ! -f "$PARAMS_FILE" ]; then
        log_error "Parameters file not found: $PARAMS_FILE"
        exit 1
    fi

    # Deploy
    az deployment group create \
        --resource-group "$RESOURCE_GROUP" \
        --name "$DEPLOYMENT_NAME" \
        --template-file main.bicep \
        --parameters "@$PARAMS_FILE" \
        --parameters \
            appName="$APP_NAME" \
            environment="$ENVIRONMENT" \
            location="$LOCATION" \
            hostingType="$HOSTING_TYPE" \
            appServiceSku="$APP_SERVICE_SKU" \
            containerImage="$CONTAINER_IMAGE" \
            sqlAdminPassword="$SQL_PASSWORD" \
        --output table

    log_success "Infrastructure deployed"
}

show_outputs() {
    log_info "Retrieving deployment outputs..."

    APP_URL=$(az deployment group show \
        -g "$RESOURCE_GROUP" \
        -n "$DEPLOYMENT_NAME" \
        --query properties.outputs.appUrl.value -o tsv)

    SQL_CONNECTION=$(az deployment group show \
        -g "$RESOURCE_GROUP" \
        -n "$DEPLOYMENT_NAME" \
        --query properties.outputs.sqlConnectionString.value -o tsv)

    APPINSIGHTS_CONNECTION=$(az deployment group show \
        -g "$RESOURCE_GROUP" \
        -n "$DEPLOYMENT_NAME" \
        --query properties.outputs.appInsightsConnectionString.value -o tsv)

    echo ""
    echo "╔════════════════════════════════════════════════════════════════╗"
    echo "║              DEPLOYMENT SUCCESSFUL                             ║"
    echo "╚════════════════════════════════════════════════════════════════╝"
    echo ""
    echo "🌐 Application URL:"
    echo "   $APP_URL"
    echo ""
    echo "🗄️  SQL Connection String:"
    echo "   $SQL_CONNECTION"
    echo ""
    echo "📊 App Insights Connection String:"
    echo "   $APPINSIGHTS_CONNECTION"
    echo ""
    echo "💡 Next steps:"

    if [ "$HOSTING_TYPE" = "appservice" ]; then
        echo "   1. Deploy your code: az webapp up --name app-${APP_NAME}-${ENVIRONMENT}"
        echo "   2. View logs: az webapp log tail --name app-${APP_NAME}-${ENVIRONMENT} -g $RESOURCE_GROUP"
    else
        echo "   1. Build and push container: az acr build --registry <ACR> --image ${APP_NAME}:latest ."
        echo "   2. Update container app: az containerapp update -n ca-${APP_NAME}-${ENVIRONMENT} -g $RESOURCE_GROUP --image <IMAGE>"
        echo "   3. View logs: az containerapp logs show -n ca-${APP_NAME}-${ENVIRONMENT} -g $RESOURCE_GROUP --follow"
    fi

    echo ""
}

# ==============================================================================
# MAIN
# ==============================================================================

main() {
    echo ""
    echo "╔════════════════════════════════════════════════════════════════╗"
    echo "║          MORPH-SPEC - Azure Infrastructure Deploy             ║"
    echo "╚════════════════════════════════════════════════════════════════╝"
    echo ""

    check_prerequisites
    create_resource_group
    generate_sql_password
    deploy_infrastructure
    show_outputs

    log_success "Deployment complete! 🚀"
}

# Run main function
main
